<template>
  <div class="container-scroller">
    <nav class="navbar default-layout col-lg-12 col-12 p-0 fixed-top d-flex align-items-top flex-row">
      <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-start">
        <div class="me-3">
          <button class="navbar-toggler navbar-toggler align-self-center" type="button" data-bs-toggle="minimize">
            <span class="icon-menu"></span>
          </button>
        </div>
        <div>
          <a class="navbar-brand brand-logo" href="../../index.html">
            <img src="../../assets/images/logo.svg" alt="logo" />
          </a>
          <a class="navbar-brand brand-logo-mini" href="../../index.html">
            <img src="../../assets/images/logo-mini.svg" alt="logo" />
          </a>
        </div>
      </div>
      <div class="navbar-menu-wrapper d-flex align-items-top">
        <ul class="navbar-nav">
          <li class="nav-item font-weight-semibold d-none d-lg-block ms-0">
            <h1 class="welcome-text">早上好，<span class="text-black fw-bold">约翰·多</span></h1>
            <h3 class="welcome-sub-text">您本周的表现摘要</h3>
          </li>
        </ul>
        <ul class="navbar-nav ms-auto">
          <li class="nav-item dropdown d-none d-lg-block">
            <a class="nav-link dropdown-bordered dropdown-toggle dropdown-toggle-split" id="messageDropdown" href="#" data-bs-toggle="dropdown" aria-expanded="false"> 选择类别 </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list pb-0" aria-labelledby="messageDropdown">
              <a class="dropdown-item py-3">
                <p class="mb-0 font-weight-medium float-left">选择类别</p>
              </a>
              <div class="dropdown-divider"></div>
              <a class="dropdown-item preview-item">
                <div class="preview-item-content flex-grow py-2">
                  <p class="preview-subject ellipsis font-weight-medium text-dark">Bootstrap 套件</p>
                  <p class="fw-light small-text mb-0">这是一个包含 16 个独特仪表板的套件</p>
                </div>
              </a>
              <a class="dropdown-item preview-item">
                <div class="preview-item-content flex-grow py-2">
                  <p class="preview-subject ellipsis font-weight-medium text-dark">Angular 套件</p>
                  <p class="fw-light small-text mb-0">您 Angular 项目所需的一切</p>
                </div>
              </a>
              <a class="dropdown-item preview-item">
                <div class="preview-item-content flex-grow py-2">
                  <p class="preview-subject ellipsis font-weight-medium text-dark">VUE 套件</p>
                  <p class="fw-light small-text mb-0">6 个高级 Vue 管理仪表板的套件</p>
                </div>
              </a>
              <a class="dropdown-item preview-item">
                <div class="preview-item-content flex-grow py-2">
                  <p class="preview-subject ellipsis font-weight-medium text-dark">React 套件</p>
                  <p class="fw-light small-text mb-0">8 个高级 React 管理仪表板的套件</p>
                </div>
              </a>
            </div>
          </li>
          <li class="nav-item d-none d-lg-block">
            <div id="datepicker-popup" class="input-group date datepicker navbar-date-picker">
              <span class="input-group-addon input-group-prepend border-right">
                <span class="icon-calendar input-group-text calendar-icon"></span>
              </span>
              <input type="text" class="form-control">
            </div>
          </li>
          <li class="nav-item">
            <form class="search-form" action="#">
              <i class="icon-search"></i>
              <input type="search" class="form-control" placeholder="搜索这里" title="搜索这里">
            </form>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link count-indicator" id="notificationDropdown" href="#" data-bs-toggle="dropdown">
              <i class="icon-mail icon-lg"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list pb-0" aria-labelledby="notificationDropdown">
              <a class="dropdown-item py-3 border-bottom">
                <p class="mb-0 font-weight-medium float-left">您有 4 条新通知</p>
                <span class="badge badge-pill badge-primary float-right">查看全部</span>
              </a>
              <a class="dropdown-item preview-item py-3">
                <div class="preview-thumbnail">
                  <i class="mdi mdi-alert m-auto text-primary"></i>
                </div>
                <div class="preview-item-content">
                  <h6 class="preview-subject fw-normal text-dark mb-1">应用程序错误</h6>
                  <p class="fw-light small-text mb-0">刚刚</p>
                </div>
              </a>
              <a class="dropdown-item preview-item py-3">
                <div class="preview-thumbnail">
                  <i class="mdi mdi-settings m-auto text-primary"></i>
                </div>
                <div class="preview-item-content">
                  <h6 class="preview-subject fw-normal text-dark mb-1">设置</h6>
                  <p class="fw-light small-text mb-0">私人消息</p>
                </div>
              </a>
              <a class="dropdown-item preview-item py-3">
                <div class="preview-thumbnail">
                  <i class="mdi mdi-airballoon m-auto text-primary"></i>
                </div>
                <div class="preview-item-content">
                  <h6 class="preview-subject fw-normal text-dark mb-1">新用户注册</h6>
                  <p class="fw-light small-text mb-0">2 天前</p>
                </div>
              </a>
            </div>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link count-indicator" id="countDropdown" href="#" data-bs-toggle="dropdown" aria-expanded="false">
              <i class="icon-bell"></i>
              <span class="count"></span>
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list pb-0" aria-labelledby="countDropdown">
              <a class="dropdown-item py-3">
                <p class="mb-0 font-weight-medium float-left">您有 7 封未读邮件</p>
                <span class="badge badge-pill badge-primary float-right">查看全部</span>
              </a>
              <div class="dropdown-divider"></div>
              <a class="dropdown-item preview-item">
                <div class="preview-thumbnail">
                  <img src="../../assets/images/faces/face10.jpg" alt="image" class="img-sm profile-pic">
                </div>
                <div class="preview-item-content flex-grow py-2">
                  <p class="preview-subject ellipsis font-weight-medium text-dark">玛丽安·加纳</p>
                  <p class="fw-light small-text mb-0">会议已取消</p>
                </div>
              </a>
              <a class="dropdown-item preview-item">
                <div class="preview-thumbnail">
                  <img src="../../assets/images/faces/face12.jpg" alt="image" class="img-sm profile-pic">
                </div>
                <div class="preview-item-content flex-grow py-2">
                  <p class="preview-subject ellipsis font-weight-medium text-dark">大卫·格雷</p>
                  <p class="fw-light small-text mb-0">会议已取消</p>
                </div>
              </a>
              <a class="dropdown-item preview-item">
                <div class="preview-thumbnail">
                  <img src="../../assets/images/faces/face1.jpg" alt="image" class="img-sm profile-pic">
                </div>
                <div class="preview-item-content flex-grow py-2">
                  <p class="preview-subject ellipsis font-weight-medium text-dark">特拉维斯·詹金斯</p>
                  <p class="fw-light small-text mb-0">会议已取消</p>
                </div>
              </a>
            </div>
          </li>
          <li class="nav-item dropdown d-none d-lg-block user-dropdown">
            <a class="nav-link" id="UserDropdown" href="#" data-bs-toggle="dropdown" aria-expanded="false">
              <img class="img-xs rounded-circle" src="../../assets/images/faces/face8.jpg" alt="Profile image"> </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown" aria-labelledby="UserDropdown">
              <div class="dropdown-header text-center">
                <img class="img-md rounded-circle" src="../../assets/images/faces/face8.jpg" alt="Profile image">
                <p class="mb-1 mt-3 font-weight-semibold">艾伦·莫雷诺</p>
                <p class="fw-light text-muted mb-0">allenmoreno@gmail.com</p>
              </div>
              <a class="dropdown-item"><i class="dropdown-item-icon mdi mdi-account-outline text-primary me-2"></i> 我的资料 <span class="badge badge-pill badge-danger">1</span></a>
              <a class="dropdown-item"><i class="dropdown-item-icon mdi mdi-message-text-outline text-primary me-2"></i> 消息</a>
              <a class="dropdown-item"><i class="dropdown-item-icon mdi mdi-calendar-check-outline text-primary me-2"></i> 活动</a>
              <a class="dropdown-item"><i class="dropdown-item-icon mdi mdi-help-circle-outline text-primary me-2"></i> 常见问题</a>
              <a class="dropdown-item"><i class="dropdown-item-icon mdi mdi-power text-primary me-2"></i> 登出</a>
            </div>
          </li>
        </ul>
        <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-bs-toggle="offcanvas">
          <span class="mdi mdi-menu"></span>
        </button>
      </div>
    </nav>
    <!-- partial -->
    <div class="container-fluid page-body-wrapper">
      <!-- partial:../../partials/_settings-panel.html -->
      <div class="theme-setting-wrapper">
        <div id="settings-trigger"><i class="ti-settings"></i></div>
        <div id="theme-settings" class="settings-panel">
          <i class="settings-close ti-close"></i>
          <p class="settings-heading">侧边栏皮肤</p>
          <div class="sidebar-bg-options selected" id="sidebar-light-theme"><div class="img-ss rounded-circle bg-light border me-3"></div>浅色</div>
          <div class="sidebar-bg-options" id="sidebar-dark-theme"><div class="img-ss rounded-circle bg-dark border me-3"></div>深色</div>
          <p class="settings-heading mt-2">头部皮肤</p>
          <div class="color-tiles mx-0 px-4">
            <div class="tiles success"></div>
            <div class="tiles warning"></div>
            <div class="tiles danger"></div>
            <div class="tiles info"></div>
            <div class="tiles dark"></div>
            <div class="tiles default"></div>
          </div>
        </div>
      </div>
      <div id="right-sidebar" class="settings-panel">
        <i class="settings-close ti-close"></i>
        <ul class="nav nav-tabs border-top" id="setting-panel" role="tablist">
          <li class="nav-item">
            <a class="nav-link active" id="todo-tab" data-bs-toggle="tab" href="#todo-section" role="tab" aria-controls="todo-section" aria-expanded="true">待办事项</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" id="chats-tab" data-bs-toggle="tab" href="#chats-section" role="tab" aria-controls="chats-section">聊天</a>
          </li>
        </ul>
        <div class="tab-content" id="setting-content">
          <div class="tab-pane fade show active scroll-wrapper" id="todo-section" role="tabpanel" aria-labelledby="todo-section">
            <div class="add-items d-flex px-3 mb-0">
              <form class="form w-100">
                <div class="form-group d-flex">
                  <input type="text" class="form-control todo-list-input" placeholder="添加待办事项">
                  <button type="submit" class="add btn btn-primary todo-list-add-btn" id="add-task">添加</button>
                </div>
              </form>
            </div>
            <div class="list-wrapper px-3">
              <ul class="d-flex flex-column-reverse todo-list">
                <li>
                  <div class="form-check">
                    <label class="form-check-label">
                      <input class="checkbox" type="checkbox">
                      团队评审会议在下午 3 点
                    </label>
                  </div>
                  <i class="remove ti-close"></i>
                </li>
                <li>
                  <div class="form-check">
                    <label class="form-check-label">
                      <input class="checkbox" type="checkbox">
                      准备演示
                    </label>
                  </div>
                  <i class="remove ti-close"></i>
                </li>
                <li>
                  <div class="form-check">
                    <label class="form-check-label">
                      <input class="checkbox" type="checkbox">
                      解决所有今天到期的低优先级票据
                    </label>
                  </div>
                  <i class="remove ti-close"></i>
                </li>
                <li class="completed">
                  <div class="form-check">
                    <label class="form-check-label">
                      <input class="checkbox" type="checkbox" checked>
                      安排下周的会议
                    </label>
                  </div>
                  <i class="remove ti-close"></i>
                </li>
                <li class="completed">
                  <div class="form-check">
                    <label class="form-check-label">
                      <input class="checkbox" type="checkbox" checked>
                      项目评审
                    </label>
                  </div>
                  <i class="remove ti-close"></i>
                </li>
              </ul>
            </div>
            <h4 class="px-3 text-muted mt-5 fw-light mb-0">事件</h4>
            <div class="events pt-4 px-3">
              <div class="wrapper d-flex mb-2">
                <i class="ti-control-record text-primary me-2"></i>
                <span>2018年2月11日</span>
              </div>
              <p class="mb-0 font-weight-thin text-gray">创建组件页面构建 js</p>
              <p class="text-gray mb-0">会话总数</p>
            </div>
            <div class="events pt-4 px-3">
              <div class="wrapper d-flex mb-2">
                <i class="ti-control-record text-primary me-2"></i>
                <span>2018年2月7日</span>
              </div>
              <p class="mb-0 font-weight-thin text-gray">与阿丽莎的会议</p>
              <p class="text-gray mb-0 ">给莎拉·格雷打电话</p>
            </div>
          </div>
          <!-- To do section tab ends -->
          <div class="tab-pane fade" id="chats-section" role="tabpanel" aria-labelledby="chats-section">
            <div class="d-flex align-items-center justify-content-between border-bottom">
              <p class="settings-heading border-top-0 mb-3 pl-3 pt-0 border-bottom-0 pb-0">朋友</p>
              <small class="settings-heading border-top-0 mb-3 pt-0 border-bottom-0 pb-0 pr-3 fw-normal">查看全部</small>
            </div>
            <ul class="chat-list">
              <li class="list active">
                <div class="profile"><img src="../../assets/images/faces/face1.jpg" alt="image"><span class="online"></span></div>
                <div class="info">
                  <p>托马斯·道格拉斯</p>
                  <p>可用</p>
                </div>
                <small class="text-muted my-auto">19 分钟前</small>
              </li>
              <li class="list">
                <div class="profile"><img src="../../assets/images/faces/face2.jpg" alt="image"><span class="offline"></span></div>
                <div class="info">
                  <div class="wrapper d-flex">
                    <p>凯瑟琳</p>
                  </div>
                  <p>离开</p>
                </div>
                <div class="badge badge-success badge-pill my-auto mx-2">4</div>
                <small class="text-muted my-auto">23 分钟前</small>
              </li>
              <li class="list">
                <div class="profile"><img src="../../assets/images/faces/face3.jpg" alt="image"><span class="online"></span></div>
                <div class="info">
                  <p>丹尼尔·拉塞尔</p>
                  <p>可用</p>
                </div>
                <small class="text-muted my-auto">14 分钟前</small>
              </li>
              <li class="list">
                <div class="profile"><img src="../../assets/images/faces/face4.jpg" alt="image"><span class="offline"></span></div>
                <div class="info">
                  <p>詹姆斯·理查森</p>
                  <p>离开</p>
                </div>
                <small class="text-muted my-auto">2 分钟前</small>
              </li>
              <li class="list">
                <div class="profile"><img src="../../assets/images/faces/face5.jpg" alt="image"><span class="online"></span></div>
                <div class="info">
                  <p>麦德琳·肯尼迪</p>
                  <p>可用</p>
                </div>
                <small class="text-muted my-auto">5 分钟前</small>
              </li>
              <li class="list">
                <div class="profile"><img src="../../assets/images/faces/face6.jpg" alt="image"><span class="online"></span></div>
                <div class="info">
                  <p>莎拉·格雷夫斯</p>
                  <p>可用</p>
                </div>
                <small class="text-muted my-auto">47 分钟前</small>
              </li>
            </ul>
          </div>
          <!-- chat tab ends -->
        </div>
      </div>
      <!-- partial -->
      <!-- partial:../../partials/_sidebar.html -->
      <nav class="sidebar sidebar-offcanvas" id="sidebar">
        <ul class="nav">
          <li class="nav-item">
            <a class="nav-link" >
              <i class="mdi mdi-grid-large menu-icon"></i>
              <span class="menu-title">仪表盘</span>
            </a>
          </li>

<!--          <li class="nav-item nav-category">管理员操作</li>-->
<!--          <li class="nav-item">-->
<!--            <a class="nav-link" data-bs-toggle="collapse" href="#ui-sb" aria-expanded="false" aria-controls="ui-sb">-->
<!--              <i class="menu-icon mdi mdi-floor-plan"></i>-->
<!--              <span class="menu-equipment">管理模块</span>-->
<!--              <i class="menu-arrow"></i>-->
<!--            </a>-->
<!--            <div class="collapse" id="ui-sb">-->
<!--              <ul class="nav flex-column sub-menu">&lt;!&ndash;pages/equipment-management/status.vue&ndash;&gt;-->
<!--                <li class="nav-item"> <a class="nav-link" v-on:click="equipment">设备管理</a></li>-->
<!--              </ul>-->
<!--            </div>-->
<!--            <div class="collapse" id="ui-sb">-->
<!--              <ul class="nav flex-column sub-menu">&lt;!&ndash;pages/equipment-management/status.vue&ndash;&gt;-->
<!--                <li class="nav-item"> <a class="nav-link" >商品管理</a></li>-->
<!--              </ul>-->
<!--            </div>-->
<!--            <div class="collapse" id="ui-sb">-->
<!--              <ul class="nav flex-column sub-menu">&lt;!&ndash;pages/equipment-management/status.vue&ndash;&gt;-->
<!--                <li class="nav-item"> <a class="nav-link" >用户管理</a></li>-->
<!--              </ul>-->
<!--            </div>-->
<!--          </li>-->

          <li class="nav-item nav-category">用户功能</li>
          <li class="nav-item">
            <a class="nav-link" data-bs-toggle="collapse" href="#ui-user" aria-expanded="false" aria-controls="ui-user">
              <i class="menu-icon mdi mdi-floor-plan"></i>
              <span class="menu-equipment">测试功能</span>
              <i class="menu-arrow"></i>
            </a>
            <div class="collapse" id="ui-user">
              <ul class="nav flex-column sub-menu"><!--pages/equipment-management/status.vue-->
                <li class="nav-item"> <a class="nav-link" v-on:click="embarkation">用户上机</a></li>
              </ul>
            </div><div class="collapse" id="ui-user">
            <ul class="nav flex-column sub-menu"><!--pages/equipment-management/status.vue-->
              <li class="nav-item"> <a class="nav-link" v-on:click="product">购买商品</a></li>
            </ul>
          </div>
          </li>



          <!--          <li class="nav-item nav-category">UI元素</li>
                    <li class="nav-item">
                      <a class="nav-link" data-bs-toggle="collapse" href="#ui-basic" aria-expanded="false" aria-controls="ui-basic">
                        <i class="menu-icon mdi mdi-floor-plan"></i>
                        <span class="menu-title">UI元素</span>
                        <i class="menu-arrow"></i>
                      </a>
                      <div class="collapse" id="ui-basic">
                        <ul class="nav flex-column sub-menu">&lt;!&ndash;pages/ui-features/buttons.html&ndash;&gt;&lt;!&ndash;pages/ui-features/dropdowns.html&ndash;&gt;&lt;!&ndash;pages/ui-features/typography.html&ndash;&gt;
                          <li class="nav-item"> <a class="nav-link" href="">按钮</a></li>
                          <li class="nav-item"> <a class="nav-link" href="">下拉菜单</a></li>
                          <li class="nav-item"> <a class="nav-link" href="">排版</a></li>
                        </ul>
                      </div>
                    </li>


                    <li class="nav-item nav-category">表单和数据</li>
                    <li class="nav-item">
                      <a class="nav-link" data-bs-toggle="collapse" href="#form-elements" aria-expanded="false" aria-controls="form-elements">
                        <i class="menu-icon mdi mdi-card-text-outline"></i>
                        <span class="menu-title">表单元素</span>
                        <i class="menu-arrow"></i>
                      </a>
                      <div class="collapse" id="form-elements">
                        <ul class="nav flex-column sub-menu">
                          <li class="nav-item"><a class="nav-link" href="pages/forms/basic_elements.html">基本元素</a></li>
                        </ul>
                      </div>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link" data-bs-toggle="collapse" href="#charts" aria-expanded="false" aria-controls="charts">
                        <i class="menu-icon mdi mdi-chart-line"></i>
                        <span class="menu-title">图表</span>
                        <i class="menu-arrow"></i>
                      </a>
                      <div class="collapse" id="charts">
                        <ul class="nav flex-column sub-menu">&lt;!&ndash;pages/charts/chartjs.html&ndash;&gt;
                          <li class="nav-item"> <a class="nav-link" href="">ChartJs</a></li>
                        </ul>
                      </div>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link" data-bs-toggle="collapse" href="#tables" aria-expanded="false" aria-controls="tables">
                        <i class="menu-icon mdi mdi-table"></i>
                        <span class="menu-title">表格</span>
                        <i class="menu-arrow"></i>
                      </a>
                      <div class="collapse" id="tables">
                        <ul class="nav flex-column sub-menu">&lt;!&ndash;pages/tables/basic-table.html&ndash;&gt;
                          <li class="nav-item"> <a class="nav-link" href="">基本表格</a></li>
                        </ul>
                      </div>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link" data-bs-toggle="collapse" href="#icons" aria-expanded="false" aria-controls="icons">
                        <i class="menu-icon mdi mdi-layers-outline"></i>
                        <span class="menu-title">图标</span>
                        <i class="menu-arrow"></i>
                      </a>
                      <div class="collapse" id="icons">
                        <ul class="nav flex-column sub-menu">&lt;!&ndash;pages/icons/mdi.html&ndash;&gt;
                          <li class="nav-item"> <a class="nav-link" href="">Mdi图标</a></li>
                        </ul>
                      </div>
                    </li>-->
          <li class="nav-item nav-category">页面</li>
          <li class="nav-item">
            <a class="nav-link" data-bs-toggle="collapse" href="#auth" aria-expanded="false" aria-controls="auth">
              <i class="menu-icon mdi mdi-account-circle-outline"></i>
              <span class="menu-title">用户页面</span>
              <i class="menu-arrow"></i>
            </a>
            <div class="collapse" id="auth">
              <ul class="nav flex-column sub-menu"><!--pages/samples/login.html-->
                <li class="nav-item"><router-link to="/" class="nav-link">登录</router-link></li>
              </ul>
            </div>
          </li>
          <!--          <li class="nav-item nav-category">帮助</li>
                    <li class="nav-item">
                      <a class="nav-link" href="#">
                        <i class="menu-icon mdi mdi-file-document"></i>
                        <span class="menu-title">文档</span>
                      </a>
                    </li>-->
        </ul>
      </nav>
      <!-- partial -->
      <!--主部分-->
      <div class="main-panel">
        <div class="container-scroller">
          <!-- 继承原有导航栏 -->
          <!-- partial:../../partials/_navbar.html -->

          <div class="container-fluid page-body-wrapper">
            <!-- 主内容区 -->
            <div class="main-panel">
              <div id="cs"><h3>测试数据</h3>

              </div>
              <div class="content-wrapper">
                <div class="row">
                  <div class="col-lg-12 grid-margin stretch-card">
                    <div class="card">
                      <div class="card-body">
                        <h4 class="card-title">网吧座位管理</h4>
                        
                        <!-- 顶部控制条 -->
                        <div class="d-flex justify-content-between align-items-center mb-4">
                          <!-- 楼层选择 -->
                          <div class="floor-selector btn-group" role="group">
                            <button id="floor1" class="btn btn-outline-primary floor-btn active">一楼</button>
                            <button id="floor2" class="btn btn-outline-primary floor-btn">二楼</button>
                    </div>
                          
                          <!-- 编辑模式开关 -->
                          <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="editModeSwitch">
                            <label class="custom-control-label" for="editModeSwitch">编辑模式</label>
                      </div>
                    </div>
                        
                        <!-- 编辑控制条 -->
                        <div id="editControls" class="edit-controls mb-3" style="display: none;">
                          <div class="btn-toolbar">
                            <div class="btn-group mr-2">
                              <button id="addSingleSeat" class="btn btn-primary">
                                <i class="mdi mdi-seat"></i> 添加座位
                              </button>
                              <button id="addCustomModule" class="btn btn-info">
                                <i class="mdi mdi-view-module"></i> 添加模块
                              </button>
                    </div>
                            <div class="btn-group mr-2">
                              <button id="clearLayout" class="btn btn-warning">
                                <i class="mdi mdi-delete-sweep"></i> 清空布局
                              </button>
                            </div>
                            <div class="btn-group">
                              <button id="submitLayout" class="btn btn-success">
                                <i class="mdi mdi-content-save"></i> 提交布局
                              </button>
                            </div>
                          </div>
                        </div>
                        
                        <!-- 座位布局容器 -->
                        <div id="seatMap" class="seat-map-container hide-grid">
                          <!-- 网格容器 -->
                      <div class="grid-container" id="gridContainer"></div>
                    </div>

                    <!-- 编辑模态框 -->
                        <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
                          <div class="modal-dialog" role="document">
                        <div class="modal-content">
                          <div class="modal-header">
                                <h5 class="modal-title" id="editModalLabel">编辑模块</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  <span aria-hidden="true">&times;</span>
                                </button>
                          </div>
                          <div class="modal-body">
                            <div class="form-group">
                                  <label for="seatNumber">编号/名称</label>
                              <input type="text" class="form-control" id="seatNumber">
                            </div>
                            <div class="form-group" id="statusGroup">
                                  <label for="seatStatus">状态</label>
                              <select class="form-control" id="seatStatus">
                                <option value="online">在线</option>
                                <option value="offline">离线</option>
                                    <option value="maintenance">维修</option>
                              </select>
                            </div>
                            <div class="form-group" id="moduleTypeGroup" style="display: none;">
                                  <label for="moduleType">模块类型</label>
                              <select class="form-control" id="moduleType">
                                <option value="wall">墙</option>
                                <option value="entrance">入口</option>
                                <option value="testing">测试区</option>
                                <option value="stairs">楼梯</option>
                                <option value="toilet">卫生间</option>
                                <option value="reception">接待台</option>
                              </select>
                            </div>
                            <div class="form-group">
                              <label for="regionSelect">区域</label>
                              <select class="form-control" id="regionSelect">
                                <option v-for="region in regions" :key="region.region_id" :value="region.region_id">
                                  {{ region.region_lv }} - {{ region.disposition }} (¥{{ region.region_price }}/h)
                                </option>
                              </select>
                            </div>
                          </div>
                          <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" id="saveChanges" data-dismiss="modal">保存</button>
                          </div>
                        </div>
                      </div>
                    </div>
                        
                        <!-- 自定义警告框 -->
                        <div id="alertOverlay" class="overlay" style="display: none;">
                          <div id="customAlert" class="custom-alert">
                            <div class="alert-header">
                              <h5 id="alertTitle">警告</h5>
                  </div>
                            <div class="alert-body">
                              <p id="alertMessage">确定要执行此操作吗？</p>
                </div>
                            <div class="alert-footer">
                              <button id="alertCancel" class="btn btn-secondary">取消</button>
                              <button id="alertConfirm" class="btn btn-primary">确认</button>
            </div>
          </div>
        </div>

                        <!-- 加载中遮罩 -->
                        <div class="loading-overlay" v-if="loading">
                          <div class="spinner"></div>
          </div>
        </div>
          </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 座位管理-->

  <!-- 添加调试容器到HTML模板部分 -->
  <div class="debug-container" style="display: none; margin-top: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
    <h5>调试信息</h5>
    <div id="debugOutput" style="white-space: pre-wrap; font-family: monospace; max-height: 300px; overflow-y: auto;"></div>
  </div>

</template>


<script>
import axios from 'axios';

export default {
  name: 'status',
  data() {
    return {
      seats: [], // 存储从服务器获取的座位信息
      loading: false, // 加载状态标志
      currentFloor: 'floor1', // 添加当前楼层状态
      editMode: false, // 添加编辑模式状态
      localSeats: {}, // 本地缓存，按楼层存储编辑状态
      hasUnsavedChanges: false, // 是否有未保存的更改
      editHistory: [], // 编辑历史
      activeModule: null, // 当前编辑的模块
      lastSelectedSeat: null, // 最后选择的座位
      saveChangesListener: null, // 保存按钮事件监听器
      regions: [], // Add regions data array
    };
  },
  methods: {
    // 初始化事件监听器
    initEventListeners() {
      // 编辑模式切换
      const editModeSwitch = document.getElementById('editModeSwitch');
      
      if (editModeSwitch) {
        editModeSwitch.addEventListener('change', (e) => {
          this.toggleEditMode(e.target.checked);
        });
      }

      // 提交布局按钮
      const submitLayoutBtn = document.getElementById('submitLayout');
      if (submitLayoutBtn) {
        submitLayoutBtn.addEventListener('click', () => {
          this.submitLayout();
        });
      }

      // 楼层切换
      const floorButtons = document.querySelectorAll('.floor-btn');
      floorButtons.forEach(button => {
        button.addEventListener('click', () => {
          // 如果有未保存的更改，提示用户
          if (this.editMode && this.hasUnsavedChanges) {
            const alertOverlay = document.getElementById('alertOverlay');
            const customAlert = document.getElementById('customAlert');
            const alertTitle = document.getElementById('alertTitle');
            const alertMessage = document.getElementById('alertMessage');
            const alertConfirm = document.getElementById('alertConfirm');
            const alertCancel = document.getElementById('alertCancel');
            
            // 设置警告信息
            alertTitle.textContent = '未保存的更改';
            alertMessage.textContent = '切换楼层前，是否保存当前楼层的更改？';
            
            // 显示警告弹窗
            alertOverlay.style.display = 'block';
            customAlert.style.display = 'block';
            
            // 确认按钮事件
            const confirmHandler = () => {
              // 提交布局
              this.submitLayout();
              
              // 切换楼层
              this.switchFloor(button.id);
              
              // 隐藏警告弹窗
              alertOverlay.style.display = 'none';
              customAlert.style.display = 'none';
              
              // 移除事件监听器
              alertConfirm.removeEventListener('click', confirmHandler);
              alertCancel.removeEventListener('click', cancelHandler);
            };
            
            // 取消按钮事件
            const cancelHandler = () => {
              // 切换楼层，不保存更改
              this.switchFloor(button.id);
              
              // 隐藏警告弹窗
              alertOverlay.style.display = 'none';
              customAlert.style.display = 'none';
              
              // 移除事件监听器
              alertConfirm.removeEventListener('click', confirmHandler);
              alertCancel.removeEventListener('click', cancelHandler);
            };
            
            // 添加事件监听器
            alertConfirm.addEventListener('click', confirmHandler);
            alertCancel.addEventListener('click', cancelHandler);
          } else {
            // 直接切换楼层
            this.switchFloor(button.id);
          }
        });
      });

      // 添加座位按钮
      const addSingleSeatBtn = document.getElementById('addSingleSeat');
      if (addSingleSeatBtn) {
        addSingleSeatBtn.addEventListener('click', () => {
          if (this.editMode) {
            this.addSeat();
          }
        });
      }

      // 添加模块按钮
      const addCustomModuleBtn = document.getElementById('addCustomModule');
      if (addCustomModuleBtn) {
        addCustomModuleBtn.addEventListener('click', () => {
          if (this.editMode) {
            this.showAddModuleMenu();
          }
        });
      }

      // 清空布局按钮
      const clearLayoutBtn = document.getElementById('clearLayout');
      if (clearLayoutBtn) {
        clearLayoutBtn.addEventListener('click', () => {
          if (this.editMode) {
            this.clearCurrentFloorLayout();
          }
        });
      }
    },
    
    // 切换楼层
    switchFloor(floorId) {
      // 移除所有按钮的active类
      document.querySelectorAll('.floor-btn').forEach(btn => btn.classList.remove('active'));
      // 添加当前按钮的active类
      document.getElementById(floorId).classList.add('active');
      // 更新当前楼层
      this.currentFloor = floorId;
      
      // 如果在编辑模式，加载对应楼层的本地缓存
      if (this.editMode) {
        // 如果没有当前楼层的缓存，从服务器数据加载
        if (!this.localSeats[this.currentFloor] || this.localSeats[this.currentFloor].length === 0) {
          this.loadSeatsToLocalCache();
        }
      }
      
      // 重新创建网格
      this.createGrid();
      // 重新渲染座位
      this.addSeatsToLayout();
    },

    // 创建网格
    createGrid() {
    const gridContainer = document.getElementById('gridContainer');
      if (!gridContainer) return;

      gridContainer.innerHTML = ''; // 清空现有内容

      // 创建12x10的网格
      for (let row = 0; row < 10; row++) {
        for (let col = 0; col < 12; col++) {
        const cell = document.createElement('div');
        cell.className = 'grid-cell';
          cell.style.gridRow = row + 1;
          cell.style.gridColumn = col + 1;

        // 添加中心点
        const center = document.createElement('div');
        center.className = 'grid-cell-center';
        cell.appendChild(center);

        // 添加坐标标签
        const label = document.createElement('div');
        label.className = 'grid-cell-label';
          label.textContent = `${row + 1},${col + 1}`;
        cell.appendChild(label);

        gridContainer.appendChild(cell);
      }
    }
    },

    // 使元素可拖动
    makeDraggable(element) {
      // 定义常量和变量
      const GRID_WIDTH = 100;
      const GRID_HEIGHT = 60;
      const DRAG_THRESHOLD = 5; // 防止微小抖动触发拖动
      
      let isDragging = false;
      let startClientX, startClientY;
      let initialLeft, initialTop;
      let lastValidPosition = { left: 0, top: 0 };
      
      // 更新数据模型中的位置属性
      const updatePositionInModel = (left, top) => {
        const elementId = element.dataset.id;
        const isNew = element.dataset.isNew === 'true';
        
        if (!elementId) return false;
        
        const col = Math.round(left / GRID_WIDTH) + 1;
        const row = Math.round(top / GRID_HEIGHT) + 1;
        
        console.log(`尝试更新元素 ${elementId} (新增: ${isNew}) 的位置: 行=${row}, 列=${col}`);
        
        let updated = false;
        let found = false;
        
        // 在本地缓存中查找并更新对应元素的位置
        Object.keys(this.localSeats).forEach(floor => {
          this.localSeats[floor].forEach(seat => {
            // 对于新增元素，我们不能依赖ID匹配，因为DOM元素的ID是临时生成的
            // 对于已有元素，我们可以直接匹配ID
            if ((!isNew && seat.id == elementId) || 
                (isNew && seat.isNew && !seat.id && seat === this.findSeatByElement(element))) {
              found = true;
              if (seat.row_position !== row || seat.col_position !== col) {
                seat.row_position = row;
                seat.col_position = col;
                updated = true;
                console.log(`成功更新元素 ${isNew ? '(新增)' : elementId} 的位置: 行=${row}, 列=${col}`);
              }
            }
          });
        });
        
        if (!found) {
          console.warn(`未找到元素 ${elementId} 在数据模型中的对应记录`);
        }
        
        if (updated) {
          // 标记有未保存的更改
          this.trackChanges();
        }
        
        return updated;
      };
      
      // 获取网格边界 - 确保准确计算
      const getGridBoundaries = () => {
        const seatMap = document.getElementById('seatMap');
        if (!seatMap) return { width: 1200, height: 600, maxLeft: 1100, maxTop: 540 };
        
        const containerWidth = seatMap.clientWidth;
        const containerHeight = seatMap.clientHeight;
        
        // 计算网格单元数量
        const colCount = Math.floor(containerWidth / GRID_WIDTH);
        const rowCount = Math.floor(containerHeight / GRID_HEIGHT);
        
        return {
          width: containerWidth,
          height: containerHeight,
          colCount: colCount,
          rowCount: rowCount,
          maxLeft: (colCount - 1) * GRID_WIDTH,
          maxTop: (rowCount - 1) * GRID_HEIGHT
        };
      };
      
      // 吸附到网格 - 优化吸附逻辑
      const snapToGrid = (left, top) => {
        const boundaries = getGridBoundaries();
        
        // 计算最近的网格位置，优先考虑靠近哪个网格点
        const col = Math.round(left / GRID_WIDTH);
        const row = Math.round(top / GRID_HEIGHT);
        
        // 计算网格对齐位置，并确保在边界内
        let snappedLeft = Math.min(Math.max(0, col * GRID_WIDTH), boundaries.maxLeft);
        let snappedTop = Math.min(Math.max(0, row * GRID_HEIGHT), boundaries.maxTop);
        
        return { left: snappedLeft, top: snappedTop };
      };
      
      // 检查是否与其他元素重叠
      const checkOverlap = (testLeft, testTop) => {
        // 保存当前位置
        const currentLeft = element.style.left;
        const currentTop = element.style.top;
        
        // 临时设置新位置用于碰撞检测
        element.style.left = `${testLeft}px`;
        element.style.top = `${testTop}px`;
        
        // 获取所有其他座位
        const otherSeats = Array.from(document.querySelectorAll('.seat-item')).filter(seat => seat !== element);
        
        // 检查重叠
        let overlapping = false;
        for (const seat of otherSeats) {
          const rect1 = element.getBoundingClientRect();
          const rect2 = seat.getBoundingClientRect();
          
          // 确定是否重叠，考虑1px的容差
          if (!(rect1.right < rect2.left + 1 || 
                rect1.left > rect2.right - 1 || 
                rect1.bottom < rect2.top + 1 || 
                rect1.top > rect2.bottom - 1)) {
            overlapping = true;
            break;
          }
        }
        
        // 恢复原始位置
        element.style.left = currentLeft;
        element.style.top = currentTop;
        
        return overlapping;
      };
      
      // 高亮目标单元格
      const highlightTargetCell = (col, row) => {
        // 移除之前的高亮
        document.querySelectorAll('.grid-cell-highlight').forEach(cell => {
          cell.classList.remove('grid-cell-highlight');
        });
        
        // 找到并高亮目标单元格
        const cells = document.querySelectorAll('.grid-cell');
        const boundaries = getGridBoundaries();
        
        // 确保索引在范围内
        if (row >= 0 && row < boundaries.rowCount && col >= 0 && col < boundaries.colCount) {
          const index = row * boundaries.colCount + col;
          if (cells[index]) {
            cells[index].classList.add('grid-cell-highlight');
          }
        }
      };
      
      // 鼠标按下事件处理
      const handleMouseDown = (e) => {
        // 如果点击的是编辑按钮或删除图标，不触发拖动
        if (e.target.classList.contains('edit-btn') || e.target.classList.contains('delete-icon')) {
          return;
        }
        
        // 记录起始位置
        startClientX = e.clientX;
        startClientY = e.clientY;
        
        // 获取元素当前位置
        initialLeft = parseInt(window.getComputedStyle(element).left) || 0;
        initialTop = parseInt(window.getComputedStyle(element).top) || 0;
        
        // 记录最后有效位置
        lastValidPosition = { left: initialLeft, top: initialTop };
        
        // 添加拖动样式
        element.classList.add('dragging');
        element.style.zIndex = '1000';
        element.style.transition = 'none';
        
        // 添加鼠标移动和松开事件
        document.addEventListener('mousemove', handleMouseMove);
        document.addEventListener('mouseup', handleMouseUp);
      };
      
      // 鼠标移动事件处理
      const handleMouseMove = (e) => {
        // 计算鼠标移动距离
        const dx = e.clientX - startClientX;
        const dy = e.clientY - startClientY;
        
        // 如果没有达到拖动阈值且尚未开始拖动，不处理
        if (!isDragging && (Math.abs(dx) < DRAG_THRESHOLD && Math.abs(dy) < DRAG_THRESHOLD)) {
          return;
        }
        
        // 标记为拖动中
        isDragging = true;
        
        // 计算新位置
        const newLeft = initialLeft + dx;
        const newTop = initialTop + dy;
        
        // 设置新位置
        element.style.left = `${newLeft}px`;
        element.style.top = `${newTop}px`;
        
        // 计算吸附位置并高亮对应单元格
        const snapped = snapToGrid(newLeft, newTop);
        const col = Math.round(snapped.left / GRID_WIDTH);
        const row = Math.round(snapped.top / GRID_HEIGHT);
        highlightTargetCell(col, row);
      };
      
      // 鼠标释放事件处理
      const handleMouseUp = () => {
        if (!isDragging) {
          document.removeEventListener('mousemove', handleMouseMove);
          document.removeEventListener('mouseup', handleMouseUp);
          
          element.classList.remove('dragging');
          element.style.zIndex = '10';
          element.style.transition = '';
          return;
        }
        
        // 获取当前位置并吸附到网格
        const currentLeft = parseInt(element.style.left) || 0;
        const currentTop = parseInt(element.style.top) || 0;
        
        // 吸附到网格
        const snapped = snapToGrid(currentLeft, currentTop);
        
        // 检查新位置是否有碰撞
        if (checkOverlap(snapped.left, snapped.top)) {
          // 如果有碰撞，恢复到最后有效位置
          element.style.left = `${lastValidPosition.left}px`;
          element.style.top = `${lastValidPosition.top}px`;
          
          // 尝试更新数据模型中的位置
          updatePositionInModel(lastValidPosition.left, lastValidPosition.top);
        } else {
          // 没有碰撞，移动到吸附位置
          element.style.left = `${snapped.left}px`;
          element.style.top = `${snapped.top}px`;
          
          // 更新最后有效位置
          lastValidPosition = { left: snapped.left, top: snapped.top };
          
          // 更新数据模型中的位置
          updatePositionInModel(snapped.left, snapped.top);
        }
        
        // 移除高亮
        document.querySelectorAll('.grid-cell-highlight').forEach(cell => {
          cell.classList.remove('grid-cell-highlight');
        });
        
        // 重置状态
        isDragging = false;
        element.classList.remove('dragging');
        element.style.zIndex = '10';
        element.style.transition = '';
        
        // 移除事件监听器
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
      };
      
      // 触摸事件处理
      const handleTouchStart = (e) => {
        if (e.target.classList.contains('edit-btn') || e.target.classList.contains('delete-icon')) {
          return;
        }
        
        e.preventDefault();

        const touch = e.touches[0];
        startClientX = touch.clientX;
        startClientY = touch.clientY;
        
        initialLeft = parseInt(window.getComputedStyle(element).left) || 0;
        initialTop = parseInt(window.getComputedStyle(element).top) || 0;
        
        lastValidPosition = { left: initialLeft, top: initialTop };
        
        element.classList.add('dragging');
        element.style.zIndex = '1000';
        element.style.transition = 'none';
        
        document.addEventListener('touchmove', handleTouchMove, { passive: false });
        document.addEventListener('touchend', handleTouchEnd);
      };
      
      const handleTouchMove = (e) => {
        e.preventDefault();

        const touch = e.touches[0];
        const dx = touch.clientX - startClientX;
        const dy = touch.clientY - startClientY;

        if (!isDragging && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)) {
          isDragging = true;
        }
        
        if (!isDragging) return;

        const newLeft = initialLeft + dx;
        const newTop = initialTop + dy;
        
        element.style.left = `${newLeft}px`;
        element.style.top = `${newTop}px`;
        
        const snapped = snapToGrid(newLeft, newTop);
        const col = Math.round(snapped.left / GRID_WIDTH);
        const row = Math.round(snapped.top / GRID_HEIGHT);
        highlightTargetCell(col, row);
      };
      
      const handleTouchEnd = () => {
        if (!isDragging) {
          document.removeEventListener('touchmove', handleTouchMove);
          document.removeEventListener('touchend', handleTouchEnd);
          
          element.classList.remove('dragging');
          element.style.zIndex = '10';
          element.style.transition = '';
          return;
      }

        // 获取当前位置并吸附到网格
        const currentLeft = parseInt(element.style.left) || 0;
        const currentTop = parseInt(element.style.top) || 0;
        
        // 吸附到网格
        const snapped = snapToGrid(currentLeft, currentTop);
        
        // 检查新位置是否有碰撞
        if (checkOverlap(snapped.left, snapped.top)) {
          element.style.left = `${lastValidPosition.left}px`;
          element.style.top = `${lastValidPosition.top}px`;
          
          // 尝试更新数据模型中的位置
          updatePositionInModel(lastValidPosition.left, lastValidPosition.top);
      } else {
          element.style.left = `${snapped.left}px`;
          element.style.top = `${snapped.top}px`;
          lastValidPosition = { left: snapped.left, top: snapped.top };
          
          // 更新数据模型中的位置
          updatePositionInModel(snapped.left, snapped.top);
        }

        document.querySelectorAll('.grid-cell-highlight').forEach(cell => {
          cell.classList.remove('grid-cell-highlight');
        });
        
      isDragging = false;
        element.classList.remove('dragging');
        element.style.zIndex = '10';
        element.style.transition = '';
        
        document.removeEventListener('touchmove', handleTouchMove);
        document.removeEventListener('touchend', handleTouchEnd);
      };
      
      // 添加事件监听器
      element.addEventListener('mousedown', handleMouseDown);
      element.addEventListener('touchstart', handleTouchStart, { passive: false });
      
      // 返回清理函数
      return () => {
        element.removeEventListener('mousedown', handleMouseDown);
        element.removeEventListener('touchstart', handleTouchStart);
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
        document.removeEventListener('touchmove', handleTouchMove);
        document.removeEventListener('touchend', handleTouchEnd);
      };
    },

    // 新增findSeatByElement方法，用于在数据中查找与DOM元素对应的座位对象
    findSeatByElement(element) {
      if (!element) return null;
      
      // 获取元素位置和名称用于匹配
      const name = element.querySelector('.seat-number')?.textContent;
      const left = parseInt(element.style.left) || 0;
      const top = parseInt(element.style.top) || 0;
      const GRID_WIDTH = 100;
      const GRID_HEIGHT = 60;
      
      // 计算大致的行列位置，用于匹配
      const col = Math.round(left / GRID_WIDTH) + 1;
      const row = Math.round(top / GRID_HEIGHT) + 1;
      
      // 在当前楼层缓存中查找匹配的座位
      let result = null;
      
      if (this.localSeats[this.currentFloor]) {
        // 首先尝试通过名称和位置匹配
        result = this.localSeats[this.currentFloor].find(seat => 
          seat.isNew && 
          seat.item_name === name &&
          Math.abs(seat.row_position - row) <= 1 &&  // 允许1格的误差
          Math.abs(seat.col_position - col) <= 1
        );
        
        // 如果找不到精确匹配，则仅通过名称匹配
        if (!result) {
          result = this.localSeats[this.currentFloor].find(seat => 
            seat.isNew && seat.item_name === name
          );
        }
      }
      
      return result;
    },

    // 修改syncVisibleElementsPositions方法，支持新增模块
    syncVisibleElementsPositions() {
      this.logDebug('同步所有可见元素的位置到数据模型...');
      const GRID_WIDTH = 100;
      const GRID_HEIGHT = 60;
      
      // 获取所有可见的座位元素
      const seatElements = document.querySelectorAll('.seat-item');
      let updateCount = 0;
      
      this.logDebug(`找到${seatElements.length}个可见元素`);
      
      seatElements.forEach(element => {
        const elementId = element.dataset.id;
        const isNew = element.dataset.isNew === 'true';
        const name = element.querySelector('.seat-number')?.textContent || '未命名';
        
        if (elementId) {
          const left = parseInt(element.style.left) || 0;
          const top = parseInt(element.style.top) || 0;
          
          this.logDebug(`检查元素 ${elementId} (${name}) ${isNew ? '- 新增' : ''}`);
          this.logDebug(`  - CSS位置: left=${left}px, top=${top}px`);
          
          // 计算行列位置
          const col = Math.round(left / GRID_WIDTH) + 1;
          const row = Math.round(top / GRID_HEIGHT) + 1;
          this.logDebug(`  - 计算的行列: 行=${row}, 列=${col}`);
          
          // 在数据模型中更新位置
          let found = false;
          Object.keys(this.localSeats).forEach(floor => {
            this.localSeats[floor].forEach(seat => {
              // 对于新增元素，我们通过找到匹配的座位对象
              // 对于已有元素，我们可以直接匹配ID
              if ((!isNew && seat.id == elementId) || 
                 (isNew && seat.isNew && !seat.id && seat === this.findSeatByElement(element))) {
                found = true;
                this.logDebug(`  - 在缓存中找到: 行=${seat.row_position}, 列=${seat.col_position}`);
                
                if (seat.row_position !== row || seat.col_position !== col) {
                  this.logDebug(`  - 更新位置: ${seat.row_position},${seat.col_position} -> ${row},${col}`);
                  seat.row_position = row;
                  seat.col_position = col;
                  updateCount++;
        } else {
                  this.logDebug(`  - 位置一致，无需更新`);
                }
              }
            });
          });
          
          if (!found) {
            this.logDebug(`  - 警告：在数据缓存中未找到元素 ${elementId} ${isNew ? '(新增)' : ''}`);
          }
        }
      });
      
      if (updateCount > 0) {
        this.logDebug(`同步完成，更新了${updateCount}个元素的位置`);
        this.trackChanges();
      } else {
        this.logDebug('所有元素位置已是最新，无需更新');
      }
    },

    // 从服务器获取所有座位信息
    getAllSeats() {
      this.loading = true;
      
      console.log('开始获取座位数据...');
      
      // 使用代理URL替代直接URL
      axios.post('/api/internet/getAllSeats')
        .then(response => {
          console.log('成功获取数据:', response);
          
          // 检查返回的数据格式 - 服务器直接返回数组
          if (response.data && Array.isArray(response.data)) {
            this.seats = response.data;
            console.log('解析的座位数据:', this.seats);
            
            // 显示测试数据表格
            this.displaySeats();
            
            // 加载本地缓存
            this.loadSeatsToLocalCache();
            
            // 将座位数据添加到布局编辑器中
            this.addSeatsToLayout();
          } else {
            console.warn('收到空响应或意外格式', response.data);
            
            // 显示错误信息
            const csElement = document.getElementById('cs');
            if (csElement) {
              csElement.innerHTML = '<h3>测试数据</h3><div class="alert alert-warning">服务器返回了空数据</div>';
            }
            
            // 清空数据并更新视图
            this.seats = [];
            this.localSeats[this.currentFloor] = [];
            this.addSeatsToLayout();
          }
        })
        .catch(error => {
          console.error('获取座位信息失败:', error);
          
          // 显示错误信息
          const csElement = document.getElementById('cs');
          if (csElement) {
            csElement.innerHTML = '<h3>测试数据</h3><div class="alert alert-danger">获取座位信息失败: ' + error.message + '</div>';
          }
          
          // 清空数据并更新视图
          this.seats = [];
          this.localSeats[this.currentFloor] = [];
          this.addSeatsToLayout();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 将座位数据添加到布局编辑器中
    addSeatsToLayout() {
      // 清空当前布局中的所有座位
      const seatMap = document.getElementById('seatMap');
      if (!seatMap) return;
      
      // 保存现有元素的位置，避免重置
      const existingPositions = {};
      const existingElements = seatMap.querySelectorAll('.seat-item');
      existingElements.forEach(el => {
        const id = el.dataset.id;
        if (id) {
          existingPositions[id] = {
            left: el.style.left,
            top: el.style.top
          };
        }
      });
      
      // 保留网格容器，移除所有座位
      const seatsToRemove = seatMap.querySelectorAll('.seat-item, .module-item');
      seatsToRemove.forEach(seat => seat.remove());
      
      // 确保gridContainer存在
      if (!document.getElementById('gridContainer')) {
        const gridContainer = document.createElement('div');
        gridContainer.className = 'grid-container';
        gridContainer.id = 'gridContainer';
        seatMap.appendChild(gridContainer);
      }
      
      // 如果本地缓存中没有当前楼层的数据，先加载
      if (!this.localSeats[this.currentFloor] || this.localSeats[this.currentFloor].length === 0) {
        this.loadSeatsToLocalCache();
      }
      
      // 遍历本地缓存中的座位数据
      this.localSeats[this.currentFloor].forEach(seat => {
        // 如果标记为删除，不显示
        if (seat.isDeleted) return;
        
        // 确定元素类型
        let type = 'seat';
        if (seat.module_type > 0) {
          type = this.getModuleTypeName(seat.module_type);
        }
        
        // 创建元素
        const seatEl = document.createElement('div');
        
        // 设置元素类和ID
        seatEl.className = type === 'seat' ? 
          `seat-item single-seat ${seat.status === 1 ? 'online' : (seat.status === 2 ? 'offline' : 'maintenance')}` : 
          `seat-item module-item ${type}`;
        
        // 设置自定义数据属性，用于跟踪
        seatEl.dataset.id = seat.id;
        seatEl.dataset.type = type;
        
        // 设置座位位置，使用已保存的位置或从数据中计算
        let x, y;
        if (existingPositions[seat.id]) {
          // 使用已保存的位置
          seatEl.style.left = existingPositions[seat.id].left;
          seatEl.style.top = existingPositions[seat.id].top;
        } else {
          // 使用数据中的位置
          x = (seat.col_position - 1) * 100;
          y = (seat.row_position - 1) * 60;
          seatEl.style.left = `${x}px`;
          seatEl.style.top = `${y}px`;
        }
        
        // 设置座位内容
        seatEl.innerHTML = `
          <span class="seat-number">${seat.item_name}</span>
          ${this.editMode ? `
            <button class="edit-btn btn btn-sm btn-light">编辑</button>
            <div class="delete-icon"></div>
          ` : ''}
        `;
        
        // 将座位添加到布局容器中
        seatMap.appendChild(seatEl);
        
        // 只在编辑模式下添加拖动功能和事件
        if (this.editMode) {
          // 添加拖动功能
          this.makeDraggable(seatEl);
          
          // 添加元素选择事件
          seatEl.addEventListener('click', (e) => {
            if (!e.target.classList.contains('edit-btn') && !e.target.classList.contains('delete-icon')) {
              this.selectModule(seatEl, seat.id);
            }
          });
          
          // 添加删除按钮事件
          const deleteIcon = seatEl.querySelector('.delete-icon');
          if (deleteIcon) {
            deleteIcon.addEventListener('click', (e) => {
              e.stopPropagation();
              this.confirmDeleteModule(seatEl, seat.id);
            });
          }
          
          // 添加编辑按钮事件
          const editBtn = seatEl.querySelector('.edit-btn');
          if (editBtn) {
            editBtn.addEventListener('click', (e) => {
              e.stopPropagation();
              this.openEditModal(seat);
            });
          }
        }
      });
    },
    
    // 选择模块
    selectModule(element, moduleId) {
      // 移除其他元素的选中状态
      document.querySelectorAll('.seat-item.selected').forEach(el => {
        if (el !== element) {
          el.classList.remove('selected');
        }
      });
      
      // 切换当前元素的选中状态
      element.classList.toggle('selected');
      
      // 如果选中，设置为当前活跃模块
      if (element.classList.contains('selected')) {
        this.activeModule = moduleId;
        this.lastSelectedSeat = element;
      } else {
        this.activeModule = null;
        this.lastSelectedSeat = null;
      }
    },
    
    // 确认删除模块
    confirmDeleteModule(element, moduleId) {
      const alertOverlay = document.getElementById('alertOverlay');
      const customAlert = document.getElementById('customAlert');
      const alertTitle = document.getElementById('alertTitle');
      const alertMessage = document.getElementById('alertMessage');
      const alertConfirm = document.getElementById('alertConfirm');
      const alertCancel = document.getElementById('alertCancel');
      
      // 设置警告信息
      alertTitle.textContent = '确认删除';
      alertMessage.textContent = '是否确定删除此模块？此操作无法撤销。';
      
      // 显示警告弹窗
      alertOverlay.style.display = 'block';
      customAlert.style.display = 'block';
      
      // 确认按钮事件
      const confirmHandler = () => {
        this.removeModuleFromLocalCache(moduleId);
        element.remove();
        
        // 隐藏警告弹窗
        alertOverlay.style.display = 'none';
        customAlert.style.display = 'none';
        
        // 移除事件监听器
        alertConfirm.removeEventListener('click', confirmHandler);
        alertCancel.removeEventListener('click', cancelHandler);
      };
      
      // 取消按钮事件
      const cancelHandler = () => {
        // 隐藏警告弹窗
        alertOverlay.style.display = 'none';
        customAlert.style.display = 'none';
        
        // 移除事件监听器
        alertConfirm.removeEventListener('click', confirmHandler);
        alertCancel.removeEventListener('click', cancelHandler);
      };
      
      // 添加事件监听器
      alertConfirm.addEventListener('click', confirmHandler);
      alertCancel.addEventListener('click', cancelHandler);
    },
    
    // 打开编辑模态框（修复Bootstrap未定义问题）
    openEditModal(module) {
      // 获取模态框元素
      const modalElement = document.getElementById('editModal');
      const seatNumber = document.getElementById('seatNumber');
      const seatStatus = document.getElementById('seatStatus');
      const moduleType = document.getElementById('moduleType');
    const statusGroup = document.getElementById('statusGroup');
    const moduleTypeGroup = document.getElementById('moduleTypeGroup');
      const regionSelect = document.getElementById('regionSelect');
      const saveChanges = document.getElementById('saveChanges');
      
      console.log('打开编辑模态框，模块数据:', module);
      
      // 清空并重新填充区域选择器
      if (regionSelect) {
        // 清空现有选项
        regionSelect.innerHTML = '';
        
        // 添加区域选项
        if (this.regions && this.regions.length > 0) {
          this.regions.forEach(region => {
            const option = document.createElement('option');
            option.value = region.region_id;
            option.textContent = `${region.region_lv} - ${region.disposition} (¥${region.region_price}/h)`;
            regionSelect.appendChild(option);
          });
    } else {
          // 如果没有区域数据，添加默认选项
          const option = document.createElement('option');
          option.value = '1';
          option.textContent = '默认区域';
          regionSelect.appendChild(option);
        }
        
        // 设置选中的区域
        regionSelect.value = module.region_id || 1;
      }
      
      // 设置模态框模式和字段
      if (module.module_type > 0) {
        // 如果是模块
      statusGroup.style.display = 'none';
      moduleTypeGroup.style.display = 'block';
        moduleType.value = this.getModuleTypeName(module.module_type);
      } else {
        // 如果是座位
        statusGroup.style.display = 'block';
        moduleTypeGroup.style.display = 'none';
        seatStatus.value = module.status === 1 ? 'online' : (module.status === 2 ? 'offline' : 'maintenance');
      }
      
      // 设置名称字段
      seatNumber.value = module.item_name;
      
      // 存储当前编辑的模块ID
      this.activeModule = module.id;
      
      // 移除之前的事件监听器（避免重复绑定）
      if (this.saveChangesListener) {
        saveChanges.removeEventListener('click', this.saveChangesListener);
      }
      
      // 保存按钮事件
      this.saveChangesListener = () => {
        const updatedProperties = {
          item_name: seatNumber.value,
          region_id: parseInt(regionSelect.value)
        };
        
        if (module.module_type > 0) {
          // 如果是模块，更新模块类型
          updatedProperties.module_type = this.getModuleTypeValue(moduleType.value);
        } else {
          // 如果是座位，更新状态
          updatedProperties.status = seatStatus.value === 'online' ? 1 : (seatStatus.value === 'offline' ? 2 : 3);
        }
        
        console.log('保存模块更新:', updatedProperties);
        
        // 更新模块属性
        this.updateModuleProperties(module.id, updatedProperties);
        
        // 更新UI显示，但不重新渲染全部
        this.updateModuleUI(module.id, updatedProperties);
        
        // 关闭模态框
        this.closeModal(modalElement);
      };
      
      // 添加保存按钮事件
      saveChanges.addEventListener('click', this.saveChangesListener);
      
      // 显示模态框
      this.showModal(modalElement);
    },
    
    // 显示提交预览
    showSubmitPreview(apiUrl, data) {
      console.log('显示提交预览...');
      
      // 创建提交预览模态框
      const backdrop = document.createElement('div');
      backdrop.className = 'modal-backdrop fade show';
      document.body.appendChild(backdrop);
      
      // 创建预览模态框HTML
      const modal = document.createElement('div');
      modal.className = 'modal fade show custom-modal';
      modal.style.display = 'block';
      modal.innerHTML = `
        <div class="modal-dialog modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">提交预览</h5>
              <button type="button" class="close" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <p>即将提交${data.length}条数据到服务器，请确认是否继续？</p>
              <div class="overflow-auto" style="max-height: 300px;">
                <pre>${JSON.stringify(data, null, 2)}</pre>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary cancel-btn">取消</button>
              <button type="button" class="btn btn-primary submit-btn">确认提交</button>
            </div>
          </div>
        </div>
      `;
      
      // 添加模态框到body
      document.body.appendChild(modal);
      document.body.classList.add('modal-open');
      
      // 取消按钮事件
      modal.querySelector('.cancel-btn').addEventListener('click', () => {
        this.closeCustomModal(modal, backdrop);
      });
      
      // 关闭按钮事件
      modal.querySelector('.close').addEventListener('click', () => {
        this.closeCustomModal(modal, backdrop);
      });
      
      // 提交按钮事件
      modal.querySelector('.submit-btn').addEventListener('click', () => {
        this.closeCustomModal(modal, backdrop);
        
        // 执行提交
        this.executeSubmit(apiUrl, data);
      });
    },
    
    // 显示模态框辅助方法
    showModal(modalElement) {
      // 添加背景遮罩
      const backdrop = document.createElement('div');
      backdrop.className = 'modal-backdrop fade show';
      document.body.appendChild(backdrop);
      
      // 显示模态框
      modalElement.classList.add('show');
      modalElement.style.display = 'block';
      document.body.classList.add('modal-open');
      
      // 添加关闭事件
      const closeBtns = modalElement.querySelectorAll('[data-dismiss="modal"]');
      closeBtns.forEach(btn => {
        btn.addEventListener('click', () => {
          this.closeModal(modalElement);
        });
      });
    },
    
    // 关闭模态框辅助方法
    closeModal(modalElement) {
      // 移除模态框显示类
      modalElement.classList.remove('show');
      modalElement.style.display = 'none';
      
      // 移除背景遮罩
      const backdrop = document.querySelector('.modal-backdrop');
      if (backdrop) {
        backdrop.remove();
      }
      
      // 移除body类
      document.body.classList.remove('modal-open');
    },
    
    // 关闭自定义模态框
    closeCustomModal(modal, backdrop) {
      if (modal) {
        document.body.removeChild(modal);
      }
      
      if (backdrop) {
        document.body.removeChild(backdrop);
      }
      
      document.body.classList.remove('modal-open');
    },
    
    // 执行提交操作
    executeSubmit(apiUrl, data) {
      console.log(`执行提交到 ${apiUrl}`);
      
      // 显示加载状态
      this.isLoading = true;
      
      // 发送网络请求
      fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
      .then(response => {
        if (!response.ok) {
          throw new Error(`服务器响应错误: ${response.status}`);
        }
        return response.json();
      })
      .then(result => {
        console.log('提交成功:', result);
        
        // 清除未保存标记
        this.hasUnsavedChanges = false;
        
        // 显示成功消息
        this.showAlert('提交成功', '布局数据已成功保存', true);
        
        // 刷新视图
        this.loadData();
      })
      .catch(error => {
        console.error('提交失败:', error);
        
        // 显示错误消息
        this.showAlert('提交失败', `保存布局时出错: ${error.message}`, false);
      })
      .finally(() => {
        // 隐藏加载状态
        this.isLoading = false;
      });
    },
    
    // 显示通用警告框
    showAlert(title, message, isSuccess) {
      console.log(`显示警告: ${title} - ${message}`);
      
      const alertOverlay = document.getElementById('alertOverlay');
      const customAlert = document.getElementById('customAlert');
      const alertTitle = document.getElementById('alertTitle');
      const alertMessage = document.getElementById('alertMessage');
      const alertConfirm = document.getElementById('alertConfirm');
      const alertCancel = document.getElementById('alertCancel');
      
      if (!alertOverlay || !customAlert || !alertTitle || !alertMessage || !alertConfirm || !alertCancel) {
        console.error('警告组件不完整，无法显示警告');
        return;
      }
      
      // 设置警告信息
      alertTitle.textContent = title;
      alertMessage.textContent = message;
      
      // 设置样式
      if (isSuccess) {
        alertTitle.style.color = '#28a745';
      } else {
        alertTitle.style.color = '#dc3545';
      }
      
      // 隐藏取消按钮
      alertCancel.style.display = 'none';
      alertConfirm.textContent = '确定';
      
      // 显示警告弹窗
      alertOverlay.style.display = 'block';
      customAlert.style.display = 'block';
      
      // 确认按钮事件
      const confirmHandler = () => {
        // 隐藏警告弹窗
        alertOverlay.style.display = 'none';
        customAlert.style.display = 'none';
        
        // 重置样式
        alertTitle.style.color = '';
        alertCancel.style.display = 'block';
        
        // 移除事件监听器
        alertConfirm.removeEventListener('click', confirmHandler);
      };
      
      // 添加事件监听器
      alertConfirm.addEventListener('click', confirmHandler);
    },

    // 初始化本地缓存
    initLocalCache() {
      // 每个楼层单独存储
      const floors = ['floor1', 'floor2'];
      floors.forEach(floor => {
        if (!this.localSeats[floor]) {
          this.localSeats[floor] = [];
        }
      });
    },

    // 将服务器座位数据加载到本地缓存
    loadSeatsToLocalCache() {
      // 清空当前楼层缓存
      this.localSeats[this.currentFloor] = [];
      
      // 获取当前楼层的座位
      const currentFloorSeats = this.seats.filter(seat => 
        seat.floor === parseInt(this.currentFloor.replace('floor', ''))
      );
      
      // 深拷贝到本地缓存
      this.localSeats[this.currentFloor] = JSON.parse(JSON.stringify(currentFloorSeats));
    },

    // 跟踪变更状态
    trackChanges() {
      this.hasUnsavedChanges = true;
      console.log('标记有未保存的更改');
    },

    // 创建新模块
    createNewModule(type, name, left, top) {
      const floor = parseInt(this.currentFloor.replace('floor', ''));
      const colPosition = Math.round(left / 100) + 1;
      const rowPosition = Math.round(top / 60) + 1;
      
      // 如果未指定位置，使用自动排版功能
      let autoPosition = { left: left, top: top };
      if (left === 0 && top === 0) {
        autoPosition = this.findNextAvailablePosition();
      }
      
      // 使用自动生成的位置
      const finalColPosition = Math.round(autoPosition.left / 100) + 1;
      const finalRowPosition = Math.round(autoPosition.top / 60) + 1;
      
      // 默认区域ID (使用第一个可用区域，如果有)
      const defaultRegionId = this.regions.length > 0 ? this.regions[0].region_id : 1;
      
      return {
        id: null, // 设置为null，让后端自动生成ID
        seat_id: type === 'seat' ? 0 : 1, // 座位类型：0是座位，1是模块
        item_name: name,
        status: type === 'seat' ? 2 : 0, // 座位默认为离线(2)，模块无状态
        row_position: finalRowPosition,
        col_position: finalColPosition,
        floor: floor,
        module_type: type === 'seat' ? 0 : this.getModuleTypeValue(type),
        region_id: defaultRegionId, // 使用默认区域ID
        isNew: true,    // 标记为新增
        type: type      // 存储类型信息
      };
    },
    
    // 查找下一个可用位置（自动排版）
    findNextAvailablePosition() {
      // 获取当前楼层已存在的所有座位
      const existingSeats = this.localSeats[this.currentFloor] || [];
      
      // 创建一个二维数组表示网格占用情况
      const grid = Array(10).fill().map(() => Array(12).fill(false));
      
      // 标记已占用的网格
      existingSeats.forEach(seat => {
        if (!seat.isDeleted) {
          const row = seat.row_position - 1;
          const col = seat.col_position - 1;
          if (row >= 0 && row < 10 && col >= 0 && col < 12) {
            grid[row][col] = true;
          }
        }
      });
      
      // 查找第一个未占用的位置
      let availableRow = 0;
      let availableCol = 0;
      
      // 先尝试在第一行找空位
      for (let col = 0; col < 12; col++) {
        if (!grid[0][col]) {
          availableCol = col;
          availableRow = 0;
          return { left: availableCol * 100, top: availableRow * 60 };
        }
      }
      
      // 如果第一行没有空位，尝试第二行
      for (let col = 0; col < 12; col++) {
        if (!grid[1][col]) {
          availableCol = col;
          availableRow = 1;
          return { left: availableCol * 100, top: availableRow * 60 };
        }
      }
      
      // 再尝试其他行
      for (let row = 2; row < 10; row++) {
        for (let col = 0; col < 12; col++) {
          if (!grid[row][col]) {
            availableRow = row;
            availableCol = col;
            return { left: availableCol * 100, top: availableRow * 60 };
          }
        }
      }
      
      // 如果所有位置都被占用，返回一个默认位置
      return { left: 0, top: 0 };
    },

    // 添加自动排版按钮
    addAutoArrangeButton() {
      return `
        <button id="autoArrangeBtn" class="btn btn-primary mt-2">
          <i class="mdi mdi-arrange-send-backward"></i> 自动排版
        </button>
      `;
    },

    // 执行自动排版
    autoArrangeLayout() {
      if (!this.editMode) return;
      
      // 确认对话框
      const alertOverlay = document.getElementById('alertOverlay');
      const customAlert = document.getElementById('customAlert');
      const alertTitle = document.getElementById('alertTitle');
      const alertMessage = document.getElementById('alertMessage');
      const alertConfirm = document.getElementById('alertConfirm');
      const alertCancel = document.getElementById('alertCancel');
      
      // 设置警告信息
      alertTitle.textContent = '自动排版';
      alertMessage.textContent = '自动排版将重新排列所有座位和模块。确定要继续吗？';
      
      // 显示警告弹窗
      alertOverlay.style.display = 'block';
      customAlert.style.display = 'block';
      
      // 确认按钮事件
      const confirmHandler = () => {
        // 获取当前楼层的所有模块
        const modules = this.localSeats[this.currentFloor].filter(m => !m.isDeleted);
        
        // 按类型分组
        const seats = modules.filter(m => m.module_type === 0);
        const walls = modules.filter(m => m.module_type === 1);
        const entrances = modules.filter(m => m.module_type === 2);
        const testingAreas = modules.filter(m => m.module_type === 3);
        const stairs = modules.filter(m => m.module_type === 4);
        const toilets = modules.filter(m => m.module_type === 5);
        const receptions = modules.filter(m => m.module_type === 6);
        
        // 重新排列座位 - 从左上角开始，每行12个
        seats.forEach((seat, index) => {
          const row = Math.floor(index / 12);
          const col = index % 12;
          seat.row_position = row + 1;
          seat.col_position = col + 1;
          seat.isModified = true;
        });
        
        // 排列其他模块 - 墙体放在底部两排
        let rowOffset = Math.ceil(seats.length / 12) + 1; // 座位下面空一行
        
        // 自动排版模块辅助函数
        const arrangeModules = (moduleList, startRow, startCol) => {
          moduleList.forEach((module, index) => {
            const row = startRow + Math.floor(index / 12);
            const col = (startCol + index) % 12;
            module.row_position = row + 1;
            module.col_position = col + 1;
            module.isModified = true;
          });
          return moduleList.length > 0 ? 
            startRow + Math.floor((moduleList.length - 1) / 12) + 1 : startRow;
        };
        
        // 排列不同类型的模块
        const wallsRow = arrangeModules(walls, rowOffset, 0);
        const entrancesRow = arrangeModules(entrances, wallsRow, 0);
        const testingRow = arrangeModules(testingAreas, entrancesRow, 0);
        const stairsRow = arrangeModules(stairs, testingRow, 0);
        const toiletsRow = arrangeModules(toilets, stairsRow, 0);
        arrangeModules(receptions, toiletsRow, 0);
        
        // 标记有更改
        this.trackChanges();
        
        // 重新渲染布局
        this.addSeatsToLayout();
        
        // 隐藏警告弹窗
        alertOverlay.style.display = 'none';
        customAlert.style.display = 'none';
        
        // 移除事件监听器
        alertConfirm.removeEventListener('click', confirmHandler);
        alertCancel.removeEventListener('click', cancelHandler);
      };
      
      // 取消按钮事件
      const cancelHandler = () => {
        // 隐藏警告弹窗
        alertOverlay.style.display = 'none';
        customAlert.style.display = 'none';
        
        // 移除事件监听器
        alertConfirm.removeEventListener('click', confirmHandler);
        alertCancel.removeEventListener('click', cancelHandler);
      };
      
      // 添加事件监听器
      alertConfirm.addEventListener('click', confirmHandler);
      alertCancel.addEventListener('click', cancelHandler);
    },

    // 添加座位模块（修复）
    addSeat() {
      if (!this.editMode) return;
      
      // 检查是否有区域数据
      if (!this.regions || this.regions.length === 0) {
        console.warn('没有可用的区域数据，正在重新获取...');
        this.getAllRegions();
        
        // 如果仍然没有数据，使用默认区域
        if (!this.regions || this.regions.length === 0) {
          this.regions = [{ region_id: 1, region_lv: 'A', disposition: '默认配置', region_price: 15 }];
        }
      }
      
      // 准备区域选项HTML
      const regionOptionsHtml = this.regions.map(region => 
        `<option value="${region.region_id}">${region.region_lv} - ${region.disposition} (¥${region.region_price}/h)</option>`
      ).join('');
      
      // 创建选择区域的模态框
      const modalHtml = `
        <div class="modal fade" id="addSeatModal" tabindex="-1" role="dialog" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">添加新座位</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                <div class="form-group">
                  <label for="newSeatName">座位编号/名称</label>
                  <input type="text" class="form-control" id="newSeatName" placeholder="例如: A01">
                </div>
                <div class="form-group">
                  <label for="newSeatRegion">选择区域</label>
                  <select class="form-control" id="newSeatRegion">
                    ${regionOptionsHtml}
                  </select>
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmAddSeat">确认添加</button>
              </div>
            </div>
          </div>
        </div>
      `;
      
      // 添加模态框到body
      const modalContainer = document.createElement('div');
      modalContainer.innerHTML = modalHtml;
      document.body.appendChild(modalContainer);
      
      // 显示模态框
      const modal = document.getElementById('addSeatModal');
      this.showModal(modal);
      
      // 确认按钮事件
      document.getElementById('confirmAddSeat').addEventListener('click', () => {
        const seatName = document.getElementById('newSeatName').value.trim() || `座位${Date.now().toString().slice(-4)}`;
        const regionId = parseInt(document.getElementById('newSeatRegion').value);
        
        console.log(`创建新座位: 名称=${seatName}, 区域ID=${regionId}`);
        
        // 查找下一个可用位置
        const position = this.findNextAvailablePosition();
        
        // 创建新座位数据
        const newSeat = this.createNewModule('seat', seatName, position.left, position.top);
        // 设置所选区域
        newSeat.region_id = regionId;
        
        console.log('新建座位数据:', newSeat);
        
        // 添加到本地缓存
        this.addModuleToLocalCache(newSeat);
        
        // 只添加新座位，不重新渲染整个布局
        this.addSingleSeatToLayout(newSeat);
        
        // 关闭模态框
        this.closeModal(modal);
        setTimeout(() => {
          modalContainer.remove();
        }, 300);
      });
      
      // 取消按钮事件
      const closeBtn = modal.querySelector('[data-dismiss="modal"]');
      if (closeBtn) {
        closeBtn.addEventListener('click', () => {
          this.closeModal(modal);
          setTimeout(() => {
            modalContainer.remove();
          }, 300);
        });
      }
    },
    
    // 添加单个座位到布局（不重新渲染所有元素）
    addSingleSeatToLayout(seat) {
      const seatMap = document.getElementById('seatMap');
      if (!seatMap) return;
      
      // 确定元素类型
      let type = 'seat';
      if (seat.module_type > 0) {
        type = this.getModuleTypeName(seat.module_type);
      }
      
      // 创建元素
      const seatEl = document.createElement('div');
      
      // 设置元素类和ID
      seatEl.className = type === 'seat' ? 
        `seat-item single-seat ${seat.status === 1 ? 'online' : (seat.status === 2 ? 'offline' : 'maintenance')}` : 
        `seat-item module-item ${type}`;
      
      // 设置自定义数据属性
      seatEl.dataset.id = seat.id || `new-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
      seatEl.dataset.type = type;
      seatEl.dataset.isNew = seat.isNew ? 'true' : 'false';  // 标记是否是新增的
      
      // 设置座位位置
      const x = (seat.col_position - 1) * 100;
      const y = (seat.row_position - 1) * 60;
        seatEl.style.left = `${x}px`;
        seatEl.style.top = `${y}px`;
        
        // 设置座位内容
        seatEl.innerHTML = `
        <span class="seat-number">${seat.item_name}</span>
          <button class="edit-btn btn btn-sm btn-light">编辑</button>
          <div class="delete-icon"></div>
        `;
        
        // 将座位添加到布局容器中
        seatMap.appendChild(seatEl);
        
        // 添加拖动功能
        this.makeDraggable(seatEl);
        
        // 添加元素选择事件
        seatEl.addEventListener('click', (e) => {
          if (!e.target.classList.contains('edit-btn') && !e.target.classList.contains('delete-icon')) {
            this.selectModule(seatEl, seat.id);
          }
        });
        
        // 添加删除按钮事件
        const deleteIcon = seatEl.querySelector('.delete-icon');
        if (deleteIcon) {
          deleteIcon.addEventListener('click', (e) => {
            e.stopPropagation();
            this.confirmDeleteModule(seatEl, seat.id);
          });
        }
        
        // 添加编辑按钮事件
        const editBtn = seatEl.querySelector('.edit-btn');
        if (editBtn) {
          editBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.openEditModal(seat);
          });
        }
      
      // 高亮显示新添加的座位
      this.selectModule(seatEl, seat.id);
    },

    // 添加自定义模块（修复）
    addCustomModule(type) {
      if (!this.editMode) return;
      
      // 查找下一个可用位置
      const position = this.findNextAvailablePosition();
      
      // 创建新模块数据
      const moduleName = type.charAt(0).toUpperCase() + type.slice(1);
      const newModule = this.createNewModule(type, moduleName, position.left, position.top);
      
      // 添加到本地缓存
      this.addModuleToLocalCache(newModule);
      
      // 只添加新模块，不重新渲染整个布局
      this.addSingleSeatToLayout(newModule);
    },

    // 显示添加模块选择菜单
    showAddModuleMenu() {
      const alertOverlay = document.getElementById('alertOverlay');
      const customAlert = document.getElementById('customAlert');
    const alertTitle = document.getElementById('alertTitle');
    const alertMessage = document.getElementById('alertMessage');
      
      // 设置标题和消息
      alertTitle.textContent = '添加模块';
      
      // 创建模块类型选择界面
      let moduleHtml = '<div class="module-selector">';
      moduleHtml += '<div class="module-type-row">';
      moduleHtml += '<button class="btn btn-outline-secondary module-btn wall-btn" data-type="wall">墙体</button>';
      moduleHtml += '<button class="btn btn-outline-secondary module-btn entrance-btn" data-type="entrance">出入口</button>';
      moduleHtml += '<button class="btn btn-outline-secondary module-btn testing-btn" data-type="testing">测试区</button>';
      moduleHtml += '</div>';
      moduleHtml += '<div class="module-type-row mt-2">';
      moduleHtml += '<button class="btn btn-outline-secondary module-btn stairs-btn" data-type="stairs">楼梯</button>';
      moduleHtml += '<button class="btn btn-outline-secondary module-btn toilet-btn" data-type="toilet">厕所</button>';
      moduleHtml += '<button class="btn btn-outline-secondary module-btn reception-btn" data-type="reception">前台</button>';
      moduleHtml += '</div>';
      moduleHtml += '</div>';
      
      alertMessage.innerHTML = moduleHtml;
      
      // 自定义弹窗按钮
      document.getElementById('alertCancel').textContent = '取消';
      document.getElementById('alertConfirm').style.display = 'none';

    // 显示弹窗
      alertOverlay.style.display = 'block';
      customAlert.style.display = 'block';
      
      // 添加模块按钮事件
      const moduleBtns = document.querySelectorAll('.module-btn');
      moduleBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
          const moduleType = e.target.dataset.type;
          
          // 隐藏当前弹窗
          alertOverlay.style.display = 'none';
          customAlert.style.display = 'none';
          document.getElementById('alertConfirm').style.display = 'block';
          
          // 显示区域选择弹窗
          this.showModuleRegionSelector(moduleType);
        });
      });
      
      // 取消按钮事件
      const cancelHandler = () => {
        alertOverlay.style.display = 'none';
        customAlert.style.display = 'none';
        document.getElementById('alertConfirm').style.display = 'block';
        
        // 移除事件监听器
        document.getElementById('alertCancel').removeEventListener('click', cancelHandler);
      };
      
      document.getElementById('alertCancel').addEventListener('click', cancelHandler);
    },
    
    // 显示模块区域选择器
    showModuleRegionSelector(moduleType) {
      // 检查是否有区域数据
      if (!this.regions || this.regions.length === 0) {
        console.warn('没有可用的区域数据，正在重新获取...');
        this.getAllRegions();
        
        // 如果仍然没有数据，使用默认区域
        if (!this.regions || this.regions.length === 0) {
          this.regions = [{ region_id: 1, region_lv: 'A', disposition: '默认配置', region_price: 15 }];
        }
      }
      
      // 准备区域选项HTML
      const regionOptionsHtml = this.regions.map(region => 
        `<option value="${region.region_id}">${region.region_lv} - ${region.disposition} (¥${region.region_price}/h)</option>`
      ).join('');
      
      // 创建区域选择模态框
      const moduleNames = {
      'wall': '墙体',
      'entrance': '出入口',
      'testing': '测试区',
      'stairs': '楼梯',
      'toilet': '厕所',
      'reception': '前台'
    };
      
      const modalHtml = `
        <div class="modal fade" id="addModuleModal" tabindex="-1" role="dialog" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">添加${moduleNames[moduleType]}</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                <div class="form-group">
                  <label for="newModuleName">模块名称</label>
                  <input type="text" class="form-control" id="newModuleName" value="${moduleNames[moduleType]}">
                </div>
                <div class="form-group">
                  <label for="newModuleRegion">选择区域</label>
                  <select class="form-control" id="newModuleRegion">
                    ${regionOptionsHtml}
                  </select>
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmAddModule">确认添加</button>
              </div>
            </div>
          </div>
        </div>
      `;
      
      // 添加模态框到body
      const modalContainer = document.createElement('div');
      modalContainer.innerHTML = modalHtml;
      document.body.appendChild(modalContainer);
      
      // 显示模态框
      const modal = document.getElementById('addModuleModal');
      this.showModal(modal);
      
      // 确认按钮事件
      document.getElementById('confirmAddModule').addEventListener('click', () => {
        const moduleName = document.getElementById('newModuleName').value.trim() || moduleNames[moduleType];
        const regionId = parseInt(document.getElementById('newModuleRegion').value);
        
        console.log(`创建新模块: 类型=${moduleType}, 名称=${moduleName}, 区域ID=${regionId}`);
        
        // 查找下一个可用位置
        const position = this.findNextAvailablePosition();
        
        // 创建新模块数据
        const newModule = this.createNewModule(moduleType, moduleName, position.left, position.top);
        // 设置所选区域
        newModule.region_id = regionId;
        
        console.log('新建模块数据:', newModule);
        
        // 添加到本地缓存
        this.addModuleToLocalCache(newModule);
        
        // 只添加新模块，不重新渲染整个布局
        this.addSingleSeatToLayout(newModule);
        
        // 关闭模态框
        this.closeModal(modal);
        setTimeout(() => {
          modalContainer.remove();
        }, 300);
      });
      
      // 取消按钮事件
      const closeBtn = modal.querySelector('[data-dismiss="modal"]');
      if (closeBtn) {
        closeBtn.addEventListener('click', () => {
          this.closeModal(modal);
          setTimeout(() => {
            modalContainer.remove();
          }, 300);
        });
      }
    },

    // 清空当前楼层布局
    clearCurrentFloorLayout() {
      const alertOverlay = document.getElementById('alertOverlay');
      const customAlert = document.getElementById('customAlert');
      const alertTitle = document.getElementById('alertTitle');
      const alertMessage = document.getElementById('alertMessage');
      const alertConfirm = document.getElementById('alertConfirm');
      const alertCancel = document.getElementById('alertCancel');
      
      // 设置警告信息
      alertTitle.textContent = '清空布局';
      alertMessage.textContent = `确定要清空${this.currentFloor === 'floor1' ? '1楼' : '2楼'}的所有布局吗？此操作无法撤销。`;
      
      // 显示警告弹窗
      alertOverlay.style.display = 'block';
      customAlert.style.display = 'block';
      
      // 确认按钮事件
      const confirmHandler = () => {
        // 标记所有非新增项为已删除
        this.localSeats[this.currentFloor].forEach(seat => {
          if (!seat.isNew) {
            seat.isDeleted = true;
          }
        });
        
        // 移除所有新增项
        this.localSeats[this.currentFloor] = this.localSeats[this.currentFloor].filter(
          seat => !seat.isNew || seat.isDeleted
        );
        
        this.trackChanges();
        
        // 重新渲染布局
        this.addSeatsToLayout();
        
        // 隐藏警告弹窗
        alertOverlay.style.display = 'none';
        customAlert.style.display = 'none';
        
        // 移除事件监听器
        alertConfirm.removeEventListener('click', confirmHandler);
        alertCancel.removeEventListener('click', cancelHandler);
      };
      
      // 取消按钮事件
      const cancelHandler = () => {
        // 隐藏警告弹窗
        alertOverlay.style.display = 'none';
        customAlert.style.display = 'none';
        
        // 移除事件监听器
        alertConfirm.removeEventListener('click', confirmHandler);
        alertCancel.removeEventListener('click', cancelHandler);
      };
      
      // 添加事件监听器
      alertConfirm.addEventListener('click', confirmHandler);
      alertCancel.addEventListener('click', cancelHandler);
    },

    // 获取模块类型值
    getModuleTypeValue(type) {
      switch(type) {
        case 'wall': return 1;
        case 'entrance': return 2;
        case 'testing': return 3;
        case 'stairs': return 4;
        case 'toilet': return 5;
        case 'reception': return 6;
        default: return 0;
      }
    },

    // 根据模块类型值获取类型名称
    getModuleTypeName(typeValue) {
      switch(typeValue) {
        case 1: return 'wall';
        case 2: return 'entrance';
        case 3: return 'testing';
        case 4: return 'stairs';
        case 5: return 'toilet';
        case 6: return 'reception';
        default: return '';
      }
    },

    // 添加新模块到本地缓存
    addModuleToLocalCache(module) {
      this.localSeats[this.currentFloor].push(module);
      this.trackChanges();
      console.log('已添加模块到本地缓存:', module);
    },

    // 从本地缓存中移除模块
    removeModuleFromLocalCache(moduleId) {
      const index = this.localSeats[this.currentFloor].findIndex(item => item.id === moduleId);
      if (index !== -1) {
        // 如果不是新增的，标记为删除
        if (!this.localSeats[this.currentFloor][index].isNew) {
          this.localSeats[this.currentFloor][index].isDeleted = true;
        } else {
          // 如果是新增的，直接从缓存中移除
          this.localSeats[this.currentFloor].splice(index, 1);
        }
        this.trackChanges();
        console.log('已从本地缓存中移除模块:', moduleId);
      }
    },

    // 更新模块位置
    updateModulePosition(moduleId, left, top) {
      const module = this.localSeats[this.currentFloor].find(item => item.id === moduleId);
      if (module) {
        const colPosition = Math.round(left / 100) + 1;
        const rowPosition = Math.round(top / 60) + 1;
        
        module.row_position = rowPosition;
        module.col_position = colPosition;
        module.isModified = true; // 标记为已修改
        
        this.trackChanges();
        console.log('已更新模块位置:', moduleId, colPosition, rowPosition);
      }
    },

    // 更新模块属性
    updateModuleProperties(moduleId, properties) {
      const module = this.localSeats[this.currentFloor].find(item => item.id === moduleId);
      if (module) {
        Object.assign(module, properties);
        module.isModified = true; // 标记为已修改
        
        this.trackChanges();
        console.log('已更新模块属性:', moduleId, properties);
      }
    },
    
    // 更新模块UI（不重新渲染整个布局）
    updateModuleUI(moduleId, properties) {
      // 查找对应的HTML元素
      const element = document.querySelector(`[data-id="${moduleId}"]`);
      if (!element) return;
      
      // 更新模块名称
      if (properties.item_name) {
        const nameEl = element.querySelector('.seat-number');
        if (nameEl) {
          nameEl.textContent = properties.item_name;
        }
      }
      
      // 更新座位状态
      if (properties.status !== undefined) {
        // 移除所有状态类
        element.classList.remove('online', 'offline', 'maintenance');
        
        // 添加新状态类
        if (properties.status === 1) {
          element.classList.add('online');
        } else if (properties.status === 2) {
          element.classList.add('offline');
        } else if (properties.status === 3) {
          element.classList.add('maintenance');
        }
      }
      
      // 更新模块类型
      if (properties.module_type !== undefined) {
        // 获取模块当前类型
        const moduleType = this.getModuleTypeName(properties.module_type);
        
        // 移除所有模块类型类
        element.classList.remove('wall', 'entrance', 'testing', 'stairs', 'toilet', 'reception');
        
        // 添加新模块类型类
        if (moduleType) {
          element.classList.add(moduleType);
        }
        
        // 更新数据属性
        element.dataset.type = moduleType;
      }
    },
    
    // 在页面上显示座位信息
    displaySeats() {
      const csDiv = document.getElementById('cs');
      if (!csDiv) {
        console.error('未找到ID为cs的元素');
        return;
      }

      if (!this.seats || this.seats.length === 0) {
        csDiv.innerHTML = '<h3>测试数据</h3><div class="alert alert-info">没有找到座位数据</div>';
        return;
      }

      console.log(`显示${this.seats.length}条座位数据`);
      
      let html = '<h3>座位信息</h3>';
      html += '<div class="table-responsive"><table class="table table-striped">';
      html += '<thead><tr>';
      html += '<th>ID</th>';
      html += '<th>Item ID</th>';
      html += '<th>Seat ID</th>';
      html += '<th>名称</th>';
      html += '<th>状态</th>';
      html += '<th>位置</th>';
      html += '<th>楼层</th>';
      html += '<th>模块类型</th>';
      html += '<th>创建时间</th>';
      html += '<th>更新时间</th>';
      html += '<th>区域ID</th>';
      html += '<th>区域等级</th>';
      html += '<th>区域配置</th>';
      html += '<th>价格</th>';
      html += '</tr></thead><tbody>';
      
      this.seats.forEach(seat => {
        // 处理状态显示
        let statusText = '';
        let statusClass = '';
        switch(seat.status) {
          case 0:
            statusText = '无座位';
            statusClass = 'text-secondary';
            break;
          case 1:
            statusText = '在线';
            statusClass = 'text-success';
            break;
          case 2:
            statusText = '离线';
            statusClass = 'text-warning';
            break;
          case 3:
            statusText = '维修';
            statusClass = 'text-danger';
            break;
          default:
            statusText = '未知';
            statusClass = 'text-muted';
        }

        // 处理模块类型显示
        let moduleTypeText = '';
        switch(seat.module_type) {
          case 0:
            moduleTypeText = '无模块';
            break;
          case 1:
            moduleTypeText = '墙体';
            break;
          case 2:
            moduleTypeText = '出入口';
            break;
          case 3:
            moduleTypeText = '测试区';
            break;
          case 4:
            moduleTypeText = '楼梯';
            break;
          case 5:
            moduleTypeText = '厕所';
            break;
          case 6:
            moduleTypeText = '前台';
            break;
          default:
            moduleTypeText = '未知';
        }
        
        html += `<tr>`;
        html += `<td>${seat.id}</td>`;
        html += `<td>${seat.item_id}</td>`;
        html += `<td>${seat.seat_id}</td>`;
        html += `<td>${seat.item_name}</td>`;
        html += `<td class="${statusClass}">${statusText}</td>`;
        html += `<td>(${seat.row_position}, ${seat.col_position})</td>`;
        html += `<td>${seat.floor}</td>`;
        html += `<td>${moduleTypeText}</td>`;
        html += `<td>${seat.created_at}</td>`;
        html += `<td>${seat.updated_at}</td>`;
        html += `<td>${seat.region_id}</td>`;
        html += `<td>${seat.region_lv}</td>`;
        html += `<td>${seat.disposition}</td>`;
        html += `<td>${seat.region_price}元/小时</td>`;
        html += `</tr>`;
      });
      
      html += '</tbody></table></div>';
      
      csDiv.innerHTML = html;
    },
    
    // 切换编辑模式
    toggleEditMode(enabled) {
      if (enabled === this.editMode) return;
      
      // 如果正在关闭编辑模式，且有未保存的更改
      if (this.editMode && !enabled && this.hasUnsavedChanges) {
        const alertOverlay = document.getElementById('alertOverlay');
        const customAlert = document.getElementById('customAlert');
        const alertTitle = document.getElementById('alertTitle');
        const alertMessage = document.getElementById('alertMessage');
        const alertConfirm = document.getElementById('alertConfirm');
        const alertCancel = document.getElementById('alertCancel');
        
        // 设置警告信息
        alertTitle.textContent = '未保存的更改';
        alertMessage.textContent = '您有未保存的布局更改。是否提交这些更改？';
        
        // 更改按钮文本
        alertConfirm.textContent = '提交更改';
        alertCancel.textContent = '放弃更改';
        
        // 显示警告弹窗
        alertOverlay.style.display = 'block';
        customAlert.style.display = 'block';
        
        // 确认按钮事件
        const confirmHandler = () => {
          // 提交布局
          this.submitLayout();
          
          // 关闭编辑模式
          this.finishToggleEditMode(enabled);
          
          // 隐藏警告弹窗
          alertOverlay.style.display = 'none';
          customAlert.style.display = 'none';
          
          // 重置按钮文本
          alertConfirm.textContent = '确认';
          alertCancel.textContent = '取消';
          
          // 移除事件监听器
          alertConfirm.removeEventListener('click', confirmHandler);
          alertCancel.removeEventListener('click', cancelHandler);
        };
        
        // 取消按钮事件
        const cancelHandler = () => {
          // 放弃更改
          this.discardChanges();
          
          // 关闭编辑模式
          this.finishToggleEditMode(enabled);
          
          // 隐藏警告弹窗
          alertOverlay.style.display = 'none';
          customAlert.style.display = 'none';
          
          // 重置按钮文本
          alertConfirm.textContent = '确认';
          alertCancel.textContent = '取消';
          
          // 移除事件监听器
          alertConfirm.removeEventListener('click', confirmHandler);
          alertCancel.removeEventListener('click', cancelHandler);
        };
        
        // 添加事件监听器
        alertConfirm.addEventListener('click', confirmHandler);
        alertCancel.addEventListener('click', cancelHandler);
      } else {
        // 直接切换编辑模式
        this.finishToggleEditMode(enabled);
      }
    },
    
    // 完成编辑模式切换
    finishToggleEditMode(enabled) {
      this.editMode = enabled;
      const editControls = document.getElementById('editControls');
      if (editControls) {
        editControls.style.display = this.editMode ? 'block' : 'none';
      }
      
      const seatMap = document.getElementById('seatMap');
      if (seatMap) {
        seatMap.classList.toggle('hide-grid', !this.editMode);
      }
      
      // 重新创建网格
      this.createGrid();
      
      // 如果进入编辑模式，重新加载本地缓存
      if (this.editMode) {
        this.loadSeatsToLocalCache();
      }
      
      // 重新渲染布局
      this.addSeatsToLayout();
    },
    
    // 放弃更改
    discardChanges() {
      // 重置本地缓存
      this.localSeats = {};
      this.initLocalCache();
      this.loadSeatsToLocalCache();
      
      // 重置变更标志
      this.hasUnsavedChanges = false;
      
      console.log('已放弃所有更改');
    },
    
    // 提交布局 - 更新以处理ID和region_id
    submitLayout() {
      console.log('准备提交布局数据...');
      if (!this.editMode) {
        console.warn('不在编辑模式下，无法提交布局');
        return;
      }
      
      // 提交前先同步所有可见元素的位置
      this.syncVisibleElementsPositions();
      
      // 额外检查所有要提交的数据，确保位置信息有效
      Object.keys(this.localSeats).forEach(floor => {
        this.localSeats[floor].forEach(module => {
          if (!module.isDeleted && (!module.row_position || !module.col_position || 
              module.row_position <= 0 || module.col_position <= 0)) {
            // 发现无效位置，记录并尝试修复
            console.log(`警告: 发现无效位置数据 - ID=${module.id}, 名称=${module.item_name}, 行=${module.row_position}, 列=${module.col_position}`);
            
            // 尝试查找对应的DOM元素获取位置
            const element = document.querySelector(`[data-id="${module.id}"]`);
            if (element) {
              const left = parseInt(element.style.left) || 0;
              const top = parseInt(element.style.top) || 0;
              const GRID_WIDTH = 100;
              const GRID_HEIGHT = 60;
              
              // 计算行列位置
              const col = Math.round(left / GRID_WIDTH) + 1;
              const row = Math.round(top / GRID_HEIGHT) + 1;
              
              console.log(`  - 从DOM元素计算得到新位置: 行=${row}, 列=${col}`);
              
              // 更新位置
              module.row_position = row;
              module.col_position = col;
            } else {
              // 如果找不到元素，使用默认值
              console.log(`  - 未找到DOM元素，使用默认位置`);
              module.row_position = module.row_position || 1;
              module.col_position = module.col_position || 1;
            }
          }
        });
      });
      
      // 收集所有楼层的变更
      const allChanges = [];
      
      // 遍历所有楼层
      Object.keys(this.localSeats).forEach(floor => {
        console.log(`处理楼层: ${floor}`);
        
        // 过滤有效的模块（未删除的）
        const floorChanges = this.localSeats[floor].filter(module => !module.isDeleted);
        console.log(`该楼层有${floorChanges.length}个模块需要提交`);
        
        allChanges.push(...floorChanges);
      });
      
      // 检查是否有数据需要提交
      if (allChanges.length === 0) {
        console.warn('没有可提交的数据');
        this.showAlert('提交警告', '没有发现任何需要提交的数据', false);
        return;
      }
      
      // 显示提交预览
      console.log(`准备提交${allChanges.length}条数据`);
      this.showSubmitPreview('/api/internet/addEquipment', allChanges);
    },
    
    // Add method to fetch all regions with enhanced error handling and debugging
    getAllRegions() {
      console.log('开始获取区域数据...');
      
      // 使用代理URL
      axios.post('/api/internet/findRegion')
        .then(response => {
          console.log('成功获取区域数据, 原始响应:', response);
          
          if (response.data && Array.isArray(response.data)) {
            this.regions = response.data;
            console.log('解析的区域数据:', this.regions);
            
            // 检查区域数据是否完整
            if (this.regions.length > 0) {
              const sample = this.regions[0];
              console.log('区域数据样例:', sample);
              
              // 检查关键字段是否存在
              if (sample.region_id === undefined || sample.region_lv === undefined || 
                  sample.disposition === undefined || sample.region_price === undefined) {
                console.warn('区域数据字段不完整，可能导致显示问题:', sample);
              }
            } else {
              console.warn('获取到的区域数据为空数组');
            }
          } else {
            console.warn('获取区域数据格式异常', response.data);
            // 创建默认区域以防止UI错误
            this.regions = [
              { region_id: 1, region_lv: 'A', disposition: '默认配置', region_price: 15 }
            ];
            console.log('已设置默认区域数据:', this.regions);
          }
        })
        .catch(error => {
          console.error('获取区域数据失败:', error);
          // 创建默认区域以防止UI错误
          this.regions = [
            { region_id: 1, region_lv: 'A', disposition: '默认配置', region_price: 15 },
            { region_id: 2, region_lv: 'B', disposition: '高级配置', region_price: 20 }
          ];
          console.log('出错后设置默认区域数据:', this.regions);
        });
    },

    // 添加调试相关方法
    showDebugPanel(show) {
      const debugContainer = document.querySelector('.debug-container');
      if (debugContainer) {
        debugContainer.style.display = show ? 'block' : 'none';
      }
    },

    logDebug(message) {
      console.log(message);
      const debugOutput = document.getElementById('debugOutput');
      if (debugOutput) {
        debugOutput.innerHTML += message + '\n';
        debugOutput.scrollTop = debugOutput.scrollHeight;
      }
    },

    // 获取模块类型名称
    getModuleTypeName(typeValue) {
      // 映射类型值到名称
      const typeMap = {
        0: 'seat',
        1: 'wall',
        2: 'entrance',
        3: 'testing',
        4: 'stairs',
        5: 'toilet',
        6: 'reception'
      };
      
      console.log('获取模块类型名称:', typeValue, '映射结果:', typeMap[typeValue] || 'unknown');
      return typeMap[typeValue] || 'unknown';
    },

    // 获取模块类型值
    getModuleTypeValue(typeName) {
      // 映射类型名称到值
      const valueMap = {
        'seat': 0,
        'wall': 1,
        'entrance': 2,
        'testing': 3,
        'stairs': 4,
        'toilet': 5,
        'reception': 6
      };
      
      console.log('获取模块类型值:', typeName, '映射结果:', valueMap[typeName] || 0);
      return valueMap[typeName] || 0;
    },

    // 加载所有数据
    loadData() {
      console.log('重新加载所有数据...');
      
      // 获取区域数据
      this.getAllRegions();
      
      // 获取座位数据
      this.getAllSeats();
    },
  },
  mounted() {
    // 初始化本地缓存
    this.initLocalCache();
    
    // 获取座位信息
    this.getAllSeats();
    
    // 获取区域信息
    this.getAllRegions();
    
    // 初始化事件监听器
    this.$nextTick(() => {
      this.initEventListeners();
      // 创建初始网格
      this.createGrid();
    });
  }
}

// ... existing code ...


</script>

<style>
  @import "@/assets/vendors/feather/feather.css";
  @import "@/assets/vendors/mdi/css/materialdesignicons.min.css";
  @import "@/assets/vendors/ti-icons/css/themify-icons.css";
  @import "@/assets/vendors/typicons/typicons.css";
  @import "@/assets/vendors/simple-line-icons/css/simple-line-icons.css";
  @import "@/assets/vendors/css/vendor-bundle-base.css";
  @import "@/utils/css/vertical-layout-light/style.css";
  /*@import "@/assets/images/favicon.png";*/

  .seat-map-container {
    position: relative;
    width: 100%;
    height: 600px;
    background: transparent;
    border: 3px solid #3a86ff; /* 修改为实体蓝色边框 */
    margin: 20px 0;
    overflow: hidden;
    touch-action: none;
    user-select: none;
    background-color: rgba(255, 255, 255, 0.8);
    box-shadow: 0 0 10px rgba(58, 134, 255, 0.3); /* 添加边框阴影 */
  }
  .seat-item {
    position: absolute;
    cursor: move;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 60px;
    border-radius: 4px;
    z-index: 10;
    touch-action: none;
    user-select: none;
    transition: box-shadow 0.2s ease;
    will-change: transform;
    transform: translate3d(0, 0, 0);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  .seat-item.dragging {
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    opacity: 0.9;
    cursor: grabbing;
  }
  .single-seat {
    background: #4CAF50;
  }
  .seat-number {
    color: white;
    font-weight: bold;
    margin-bottom: 4px;
  }
  .edit-btn {
    padding: 2px 8px;
    font-size: 12px;
    border-radius: 3px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    opacity: 0;
    transition: opacity 0.2s ease, background-color 0.2s ease;
    background-color: rgba(255, 255, 255, 0.9);
    border: none;
    cursor: pointer;
  }
  .seat-item:hover .edit-btn {
    opacity: 1;
  }
  .edit-btn:hover {
    background-color: #fff;
  }
  .delete-icon {
    position: absolute;
    left: 5px;
    top: 5px;
    width: 12px;
    height: 12px;
    background-color: #ff0000;
    border-radius: 50%;
    cursor: pointer;
    z-index: 11;
    box-shadow: 0 1px 3px rgba(0,0,0,0.3);
    transition: transform 0.2s ease;
  }
  .delete-icon:hover {
    transform: scale(1.2);
  }
  .grid-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 1200px;
    height: 600px;
    display: grid;
    z-index: 1;
    pointer-events: none;
    background-image: 
        linear-gradient(to right, #f0f0f0 1px, transparent 1px),
        linear-gradient(to bottom, #f0f0f0 1px, transparent 1px);
    background-size: 100px 60px;
  }
  .grid-cell {
    border: 1px dashed #ccc;
    position: relative;
    transition: background-color 0.2s ease;
  }
  .grid-cell:hover {
    background-color: rgba(0, 0, 0, 0.05);
  }
  .grid-cell-center {
    position: absolute;
    width: 6px;
    height: 6px;
    background: rgba(0, 0, 255, 0.3);
    border-radius: 50%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 5;
  }
  .grid-cell-label {
    position: absolute;
    font-size: 10px;
    color: #999;
    bottom: 2px;
    right: 2px;
    opacity: 0.7;
  }
  /* 拖动时的视觉反馈 */
  .seat-item.dragging::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border: 2px dashed #4CAF50;
    border-radius: 4px;
    pointer-events: none;
    animation: pulse 1s infinite;
  }
  @keyframes pulse {
    0% {
        opacity: 0.5;
        transform: scale(1);
    }
    50% {
        opacity: 0.8;
        transform: scale(1.02);
    }
    100% {
        opacity: 0.5;
        transform: scale(1);
    }
  }
  /* 编辑模式相关样式 */
  .edit-mode-container {
    margin-top: 10px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .edit-mode-label {
    font-weight: 600;
    font-size: 16px;
    color: #555;
  }
  .form-switch .form-check-input {
    width: 3em;
    height: 1.5em;
    cursor: pointer;
  }
  .form-check-input:checked {
    background-color: #198754;
    border-color: #198754;
  }
  /* 隐藏网格元素（在非编辑模式下） */
  .hide-grid .grid-cell {
    border-color: transparent;
  }
  .hide-grid .grid-cell-center,
  .hide-grid .grid-cell-label {
    display: none;
  }
  .flash {
    animation: flash-animation 0.5s ease-in-out;
  }
  @keyframes flash-animation {
    0% { opacity: 1; }
    50% { opacity: 0.5; }
    100% { opacity: 1; }
  }
  .offline {
    background-color: #888888;
    box-shadow: 0 2px 4px rgba(136, 136, 136, 0.2);
  }
  .maintenance {
    background-color: #FFA500;
    box-shadow: 0 2px 4px rgba(255, 165, 0, 0.2);
  }
  .online {
    background-color: #4CAF50;
    box-shadow: 0 2px 4px rgba(76, 175, 80, 0.2);
  }
  /* 自定义模块样式 */
  .module-item {
    position: absolute;
    cursor: move;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: left 0.3s ease, top 0.3s ease;
    width: 100px;
    height: 60px;
    border-radius: 4px;
    z-index: 10;
    color: white;
    font-weight: bold;
  }
  .delete-icon {
    position: absolute;
    left: 5px;
    top: 5px;
    width: 12px;
    height: 12px;
    background-color: #ff0000;
    border-radius: 50%;
    cursor: pointer;
    z-index: 11;
    box-shadow: 0 1px 3px rgba(0,0,0,0.3);
  }
  /* 自定义警告弹窗 */
  .custom-alert {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.3);
    z-index: 1050;
    min-width: 300px;
    text-align: center;
    display: none;
  }
  .custom-alert-title {
    font-size: 18px;
    margin-bottom: 10px;
    font-weight: bold;
  }
  .custom-alert-message {
    margin-bottom: 15px;
  }
  .custom-alert-buttons {
    display: flex;
    justify-content: center;
    gap: 10px;
  }
  .custom-alert-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0.5);
    z-index: 1040;
    display: none;
  }
  .wall {
    background-color: #6c757d;
    box-shadow: 0 2px 4px rgba(108, 117, 125, 0.2);
  }
  .entrance {
    background-color: #28a745;
    box-shadow: 0 2px 4px rgba(40, 167, 69, 0.2);
  }
  .testing {
    background-color: #ffc107;
    box-shadow: 0 2px 4px rgba(255, 193, 7, 0.2);
  }
  .stairs {
    background-color: #17a2b8;
    box-shadow: 0 2px 4px rgba(23, 162, 184, 0.2);
  }
  .toilet {
    background-color: #1e7e34;
    box-shadow: 0 2px 4px rgba(30, 126, 52, 0.2);
  }
  .reception {
    background-color: #fd7e14;
    box-shadow: 0 2px 4px rgba(253, 126, 20, 0.2);
  }
  .floor-selector {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .floor-btn {
    margin-right: 5px;
  }
  .floor-btn.active {
    background-color: #007bff;
    color: white;
  }

  /* 添加网格单元格高亮样式 */
  .grid-cell-highlight {
    background-color: rgba(58, 134, 255, 0.2);
    border: 1px solid rgba(58, 134, 255, 0.5);
    z-index: 2;
  }

  /* 添加模块选择器样式 */
  .module-selector {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .module-type-row {
    display: flex;
    gap: 10px;
    justify-content: center;
  }
  
  .module-btn {
    padding: 8px 15px;
    flex: 1;
    max-width: 100px;
  }
  
  /* 选中样式 */
  .seat-item.selected {
    box-shadow: 0 0 0 3px #007bff !important;
    z-index: 50;
  }
  
  /* 加载状态 */
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0.5);
    z-index: 2000;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .spinner {
    width: 50px;
    height: 50px;
    border: 5px solid #f3f3f3;
    border-top: 5px solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  /* 模块按钮样式 */
  .wall-btn:hover {
    background-color: #6c757d;
    color: white;
  }
  
  .entrance-btn:hover {
    background-color: #28a745;
    color: white;
  }
  
  .testing-btn:hover {
    background-color: #ffc107;
    color: white;
  }
  
  .stairs-btn:hover {
    background-color: #17a2b8;
    color: white;
  }
  
  .toilet-btn:hover {
    background-color: #1e7e34;
    color: white;
  }
  
  .reception-btn:hover {
    background-color: #fd7e14;
    color: white;
  }

  .edit-mode-controls {
    margin-top: 10px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .edit-mode-label {
    font-weight: 600;
    font-size: 16px;
    color: #555;
  }

  .form-switch .form-check-input {
    width: 3em;
    height: 1.5em;
    cursor: pointer;
  }

  /* 美化编辑控制按钮 */
  .edit-controls {
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    margin-bottom: 20px !important;
  }

  .edit-controls .btn {
    padding: 8px 16px;
    border-radius: 4px;
    font-weight: 500;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }

  .edit-controls .btn i {
    font-size: 18px;
  }

  .edit-controls .btn-primary {
    background: #4361ee;
    border-color: #4361ee;
  }

  .edit-controls .btn-primary:hover {
    background: #3a56d4;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(67, 97, 238, 0.2);
  }

  .edit-controls .btn-info {
    background: #3f37c9;
    border-color: #3f37c9;
  }

  .edit-controls .btn-info:hover {
    background: #362fbf;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(63, 55, 201, 0.2);
  }

  .edit-controls .btn-warning {
    background: #ff9e00;
    border-color: #ff9e00;
    color: white;
  }

  .edit-controls .btn-warning:hover {
    background: #e88e00;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(255, 158, 0, 0.2);
  }

  .edit-controls .btn-success {
    background: #38b000;
    border-color: #38b000;
  }

  .edit-controls .btn-success:hover {
    background: #32a000;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(56, 176, 0, 0.2);
  }

  .btn-group {
    margin-right: 10px;
  }
</style>